gpt4 book ai didi

c++ - 如何编写一个 C++ 函数,根据处理返回不同类型的 std::list?

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:12 27 4
gpt4 key购买 nike

下面的代码在指定的地方有什么问题?我想根据程序在文件中某处读取的内容返回整数或字符或字符串的列表。我尝试了下面的代码,但它抛出了错误。如您所见,我对模板有点弱。

template <class T> 
std::list<T> function1(int type)
{
using namespace std;
if (1 == type)
return list<int>(3, 100); / No error
else if (2 == type){
list<wchar_t> temp;
temp.push_back(L'a'); // C2664 error here
return temp;
}else if (3 == type){
list<wstring> temp;
temp.push_back(L"a"); // C2664 error here
return temp;
}else
return nullptr; // C2664 error here
}

我已经指出了“visual studio 2013 社区版更新 4”抛出编译器错误 C2664 的要点。我怎么能这样写,我可以根据里面的处理得到列表?错误之一如下。

Error   1   error C2664: 'std::list<int,std::allocator<_Ty>>::list(std::initializer_list<_Ty>,const std::allocator<_Ty> &)' : cannot convert argument 1 from 'std::list<wchar_t,std::allocator<wchar_t>>' to 'const std::list<int,std::allocator<_Ty>> &'

最佳答案

那是不可能的,模板需要在编译时解析,但是 type 的值在那里是未知的。您需要使用一些间接寻址,例如 boost::variant或非模板化界面。或者更确切地说,使用一种完全不同的方法。

关于c++ - 如何编写一个 C++ 函数,根据处理返回不同类型的 std::list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com