我有一个模板类,它有一个大的泛型成员函数,所以读起来不太容易。 我决定将此函数移到类体之外,并在与“.hpp”同名的“.cpp”文件中实现它,但我无法通过编译。 如果我以专门的形式而不是通用的形式实现它,它可以被编译/链接,即使它也保存在“*.cpp”文件中。
代码如下:
ClassC.hpp:
#pragma once
template <typename T>
class ClassC {
public:
ClassC( T* p ) : d( p ) {};
void show();
private:
T* d;
};
C类.cpp
#include <iostream>
#include "ClassC.hpp"
#include "ClassD.hpp"
using namespace std;
// this is a specialized version, and can be compiled/linked.
template <>
void ClassC<ClassD>::show() {
cout << "This is a specialized ClassC." << endl;
};
// this is my generic version, and can not be compiled.
template <typename T>
void ClassC::show() {
cout << "This is a generic ClassC." << endl;
};
/* */
D类.hpp
#pragma once
#include "ClassC.hpp"
class ClassD {
public:
ClassD(): c( this ) {};
void show();
private:
ClassC<ClassD> c;
};
D类.cpp
#include <iostream>
#include "ClassD.hpp"
using namespace std;
void ClassD::show() {
c.show();
cout << "This is ClassD" << endl;
};
main.cpp
#include "ClassD.hpp"
int main() {
ClassD d;
d.show();
return 0;
};
最佳答案
有几种方法可以解决此问题:
- 显式实例化
- 包容模型
- 分离模型
显式实例化与模板特化示例类似:
template my_class<size_t>::my_class();
显式实例化 my_class<T>
的构造函数对于类型 size_t。
包容模型
代码要么写在 .h 文件内,这是处理此问题的一种非常常见的方法,要么我们在声明该模板的头文件中包含模板的定义,因此:
#include "my_file.cpp"
.
分离模型
使用关键字export
。然而,我几乎从未使用过它,因为它执行得很慢。
export template <typename T>
struct C {};
关于c++ - 如何在模板类声明体之外实现成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54440908/