c++ - 在头文件中定义模板,在派生类中的 cpp 文件中定义

标签 c++

<分区>

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

关于c++ - 在头文件中定义模板,在派生类中的 cpp 文件中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960820/

相关文章:

c++ - 使用声明修改派生类中的访问说明符

c++ - boost odeint : controlled stepper with custom class and vector space algebra

c++ - 如何将 QString 复制到 wchar_t 缓冲区

c++ - 使用 Qt visual studio 插件的任何缺点

c++ - 在编译时重复到已知N的std::tuple

c++ - 我们可以在C++代码中使用Coremotion之类的iOS框架吗

c++ - 用于具有不同签名的函数的枚举切换器

c++ - 带有 CMake 的 yaml-cpp undefined reference

C++ 真正的方法重载?

c++ - GDB 在调试时损坏 - 没有控制台输出?