C ++模板,函数在类中定义?

时间:2013-08-16 14:12:26

标签: c++ templates struct

Class.h

template<class T>
  struct AStruct
  {
     //stuff
  };

class aClass
{
  template<class T>
  void setStruct(const AStruct<T>& s)
  {
    theStruct = s; 
  }

private:
  template<class T>
  AStruct<T> theStruct;  //this is not liked.  "multiple template parameter lists are not allowed" are one of the errors I get... 
}; 

相当混乱但仍然,我想知道可以做些什么...我试过玩了一下但没有运气......而且,只有标准库请!

3 个答案:

答案 0 :(得分:4)

template<class T>
struct AStruct{
};

template<class T>         //<-- the template must be here
class aClass {
public:
    void setStruct(const AStruct<T>& s){
         theStruct = s; 
    }
private:
    AStruct<T> theStruct; //<-- To construct this variable
};

答案 1 :(得分:2)

删除template<class T>

template<class T>
struct AStruct{
 //stuff
};

template<class T>
class aClass{

 void setStruct(const AStruct<T>& s){
  theStruct = s; 
}

private:
AStruct<T> theStruct;   
}; 

您已将AStruct定义为模板

答案 2 :(得分:2)

如果您持有的是类模板的成员,那么您需要一个类模板,或者您需要为模板参数提供一个类型。看起来你需要前者:

template<class T>
class aClass
{
  void setStruct(const AStruct<T>& s){
   theStruct = s; 
  }

private:
  AStruct<T> theStruct; // data member is class template
};