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

writing templated member function over container type outside a template class

本文关键字:成员 函数 类型      更新时间:2023-10-16

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

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等等。

但是我得到编译错误

" prototype for Initialize (T&)不匹配类Foo中的任何"候选是Initialize (container_t&)"…

这解决你的问题了吗?

template <class traits>
void Foo<traits>::Initialize( typename traits::container_t& t ) {
  // code
}
template <typename T> 
//        vvvvvv   ^^                    mismatch!!!
void Foo <traits>::Initialize (T& data)  
{ 
   fill the data 
}

模板实参和传递给类模板的实参不相同。你需要解决这个问题。另外,我建议不要将模板参数命名为与稍后在该位置使用的类型相同的名称和拼写,因为这通常会引起混淆。你可以改变大小写:

class traits { … };
template <typename Traits>
class Foo { … };