c++ - 在模板类之外的容器类型上编写模板化成员函数

标签 c++ templates c++11

我有一个模板类,我试图在类定义之外定义一个成员函数,如下所示:

class traits {
  typedef std::vector<int> container_t;
  ...other typedefs// 

};

template <class traits>
class Foo {
  typedef typename traits::container_t  container_t  
  // where container_t = std::vector <int>

  // member function to be templatized over container type
  void Initialize (container_t&);

private:
  container_t  temp;   //temp is of type std::vector<int>

};


template <typename T> 
void Foo <traits>::Initialize (T& data)  
{ 
   fill the data 
}

我希望函数 Initialize 采用模板容器类型 -- container_t,其中 container_t 可以是 std::vector 或 std::set 等等。

但是我得到了编译器错误

“初始化 (T&) 的原型(prototype)与 Foo 类中的任何原型(prototype)都不匹配” “候选人是 Initialize (container_t&)” ...

最佳答案

这是否解决了您的问题?

template <class traits>
void Foo<traits>::Initialize( typename traits::container_t& t ) {
  // code
}

关于c++ - 在模板类之外的容器类型上编写模板化成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22495864/

相关文章:

c++ - Qt 容器类的通用搜索算法

c++ - 将 Microsoft COM IDL 编译/翻译为地道的 C++?

c++ - 如何检查分离的 std::thread 是否仍在运行?

c++ - 在 C++11 上模拟通用/模板化 lambda

c++ - 如何连接通过 cython 返回对象引用的 C++ 函数

c++ - 第二个条件中的 i & (1<<j)) 是什么意思?

c++ - 类成员函数作为继承情况下的模板参数

c++ - 将成员函数指针传递给 gcc 上的模板化成员函数时出现问题

c++ - 智能指针的模板特化与普通指针完全一样

boost - Boost::variant与无序映射