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

标签 c++ templates c++11 stl stdlist

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

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/

相关文章:

iphone - 在 iOS 上使用 std 写入文件

c++ - 为什么在C++宏上扩展为注释时会出现 “Expected a declaration”错误?

具有成员函数的 C++ 结构与具有公共(public)变量的类

c++ - 如果不存在,则调用自由函数而不是方法

c++ - 程序应何时通知用户它无法打开文件?

c++ - 对象的性能影响

c++ - 别名可变参数模板函数

c++ - `decltype` 作为模板函数声明中模板类型规范的一部分

c++ - 为 STL 分配器实现 select_on_container_copy_construction()

c++ - 静态全局函数的静态局部成员?