C++ “不带模板参数使用”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10263017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"used without template parameters"
提问by synaptik
I realize similar questions have been asked before, but I read a couple of those and still don't see where I'm going wrong. When I simply write my class without separating the prototype from the definition, everything works fine. The problem happens when I separate the prototype and definition as shown below:
我意识到以前也有人问过类似的问题,但我读了其中的几个,但仍然看不出我哪里出错了。当我简单地编写我的类而不将原型与定义分开时,一切正常。当我将原型和定义分开时会出现问题,如下所示:
template<class T> class VisitedSet {
public:
VisitedSet();
int getSize();
void addSolution(const T& soln);
void evaluate();
private:
vector<T> vec;
int iteration;
};
And as an example of a definition that gives me this error:
作为给我这个错误的定义的一个例子:
int VisitedSet::getSize() {
return vec.size();
I've never made a templated class before, so please pardon me if the problem here is trivial.
我以前从未制作过模板化课程,所以如果这里的问题微不足道,请原谅我。
回答by Jon Purdy
VisitedSet
is a template, not a class, so you can't use VisitedSet
in a nested name specifier such as VisitedSet::getSize()
. Just as you specified the declaration of class VisitedSet<T>
for all class T
, you must specify the definition of VisitedSet<T>::getSize()
for all class T
:
VisitedSet
是模板,而不是类,因此您不能VisitedSet
在嵌套名称说明符中使用,例如VisitedSet::getSize()
. 正如您指定class VisitedSet<T>
for all的声明一样class T
,您必须指定VisitedSet<T>::getSize()
for all的定义class T
:
template<class T>
int VisitedSet<T>::getSize() {
// ^^^
return vec.size();
}
The name of a template can, however, be used as though it were a class withina template definition:
模板的名称可以,但是,使用,就好像是一个类中的模板定义:
template<class T>
struct Example {
Example* parent;
T x, y;
};
In this case, Example
is short for Example<T>
.
在这种情况下,Example
是 的缩写Example<T>
。
回答by chris
You want this:
你要这个:
template <class T>
int VisitedSet<T>::getSize() {
return vec.size();
}
回答by Bo Persson
You have to state the template parameter in the definition as well
您还必须在定义中说明模板参数
template<class T>
int VisitedSet<T>::getSize() {
return vec.size();
}
otherwise the compiler cannot match it to the declaration. For example, there could be specializations for some parameter types.
否则编译器无法将其与声明匹配。例如,可能有一些参数类型的特化。
回答by d_inevitable
You need to let your compiler know that you are implementing a method in template function:
您需要让编译器知道您正在模板函数中实现一个方法:
template<typename T>
int VisitedSet<T>::getSize() {
return vec.size();
}