模板成员函数的实例化
Instantiation of template member function
In Class.h
:
class Class {
public:
template <typename T> void function(T value);
};
In Class.cpp
:
template<typename T> void Class::function(T value) {
// do sth
}
In main.cpp
:
#include "Class.h"
int main(int argc, char ** argv) {
Class a;
a.function(1);
return 0;
}
我得到一个链接错误,因为Class.cpp
从未实例化void Class::function<int>(T)
。您可以使用以下命令显式实例化模板类:
template class std::vector<int>;
如何显式实例化非模板类的模板成员?
谢谢,
可以在Class.cpp
中使用以下语法:
template void Class::function(int);
template实参可以省略,因为类型演绎适用于函数模板。因此,上面的代码相当于下面的代码,只是更简洁:
template void Class::function<int>(int);
注意,没有必要指定函数形参的名称——它们不是函数(或函数模板)签名的一部分。
您在Class.cpp
中尝试过以下操作吗?
template void Class::function<int>(int value);
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 模板化类构造函数的模板实例化
- 何时需要实例化函数模板定义?
- clang:使用 O3 导出隐式实例化函数的符号
- 如何调用模板函数的每个实例化函数
- 使用泛型类型显式实例化函数模板
- 使用自动>decltype方法显式实例化函数
- MSVC 编译器实例化函数模板的默认定义,即使存在专用化
- 如何使用模板模板参数显式实例化函数
- 实例化函数模板的编译问题
- Lua到c++,用于实体修改的实例化函数
- 当类型参数为空时,无法实例化函数模板
- 调用实例化函数时发生链接器错误
- 实例化函数的多个模板并在运行时选择的通用解决方案
- 使用不完整类型显式实例化函数模板
- 实例化函数模板时出错
- 禁止使用迭代器形参实例化函数模板