Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
我试图在头文件中定义一个模板,并在 cpp 文件中定义它,并且模板应该在派生类中定义。所以这就是我得到的:
头文件:
#ifndef ........
#define .....
template <class mytypename>
class abcBaseClass:public abcDerivedClass{
public:
mytypename getvalue(char*)
};
#endif
源文件:
mytypename abcDerivedClass<mytypename>::getvalue(char* name){
}
我只是想知道这样做是否正确?
这就是我要实现的目标......我想要调用电话的最终方式是
double x = a->getvalue<double>(char)
类似的问题已经在 SO 上被问过很多次了。
但是无论如何...
首先,你犯了一些语法错误。
代替
#ifndef ........
#define .....
template <class typename>
class abcBaseClass:public abcDerivedClass{
public:
typename getvalue(char*);
};
#endif
应该是这样的
#ifndef ........
#define .....
template <typename T>
class abcBaseClass:public abcDerivedClass{
public:
T getvalue(char*);
};
// Definition follow in this file!
// For reasons or work-arounds, read below.
#endif
此外,模板声明和定义都应该放在同一个文件中。
一个异常(exception)是当您将该模板实例化为模板定义所在的源文件中的某种类型时。
像这样。
#include "this_template.h"
template <typename T>
// all sorts of definitions...
// Explicit instantiate this template!!!!
template class abcBaseClass<Your_Type_Goes_Here>;
请注意,此方法的一个根本缺陷是,您只能在程序的其他任何地方使用在此源文件中显式实例化的类型。尝试用其他类型实例化此模板将导致链接器提示无法找到匹配的定义。
如果您坚持模板是通用的并且在其他地方定义模板类。
您可以将定义放入另一个头文件中,只需将其命名为 this_template_impl.h
并将 this_template.h
包含在 this_template_impl.h
然后,在您的源文件中,您编写的不是#include "this_template.h"
,而是#include "this_template_impl.h