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