Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++模板,函数定义在一个类中?_C++_Templates_Struct - Fatal编程技术网

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

C++模板,函数定义在一个类中?,c++,templates,struct,C++,Templates,Struct,h班 相当混乱,但我想知道能做些什么。。。我试着玩了一会儿,但运气不好。。。另外,请只使用标准库 删除模板 您已经将AStruct定义为模板如果您持有的成员是类模板,则需要类模板,或者需要为模板参数提供类型。似乎你需要前者: template<class T> struct AStruct{ //stuff }; template<class T> class aClass{ void setStruct(const AStruct<T>& s

h班

相当混乱,但我想知道能做些什么。。。我试着玩了一会儿,但运气不好。。。另外,请只使用标准库

删除模板


您已经将AStruct定义为模板

如果您持有的成员是类模板,则需要类模板,或者需要为模板参数提供类型。似乎你需要前者:

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

template<class T>
class aClass{

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

private:
AStruct<T> theStruct;   
}; 
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
};

你还没有问过一个问题。如果构造器不知道t是什么,它将如何构造?如果您有一个需要模板的变量,则需要模板化整个类。这是不幸的。我希望有另一种方式…:没有语言或标准库支持在运行时更改变量的类型,因为这段代码试图这样做;但是像这样的动态类型库可能对这类事情很有用。我在编译时实际上不知道t是什么,所以如果我删除它,它会说标识符t未定义,但现在您尝试为不存在的类型t实例化AStruct。它或者需要为现有类型实例化,选择这个作为正确答案的动机:你和安德烈都有相同的答案,而且似乎在同一时间回答了,所以为了公平起见,这个答案是通过正面或反面选择的。
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
};
template<class T>
class aClass
{
  void setStruct(const AStruct<T>& s){
   theStruct = s; 
  }

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