模板成员函数的实例化 [英] Instantiation of template member function
问题描述
在Class.h
class Class {
public:
template <typename T> void function(T value);
};
在Class.cpp中
In Class.cpp
template<typename T> void Class::function(T value) {
// do sth
}
in main.cpp
In main.cpp
#include "Class.h"
int main(int argc, char ** argv) {
Class a;
a.function(1);
return 0;
}
我得到一个链接错误,因为Class.cpp从不实例化void Class :: function (T)。
你可以显式实例化一个模板类:
I get a linked error because Class.cpp never instantiate void Class::function(T). You can explicitly instantiate a template class with :
template class std::vector<int>;
如何显式实例化非模板类的模板成员?
How do you explicitly instantiate a template member of a non-template class ?
感谢,
Thanks,
推荐答案
您可以在 .cpp
:
template void Class::function(int);
模板参数可以省略,因为类型推导,适用于函数模板。因此,上面的内容相当于下面的内容:
The template argument can be omitted because of type deduction, which works for function templates. Thus, the above is equivalent to the following, just more concise:
template void Class::function<int>(int);
注意,没有必要指定函数参数的名称 - 它们不是函数(或函数模板)的签名。
Notice, that it is not necessary to specify the names of the function parameters - they are not part of a function's (or function template's) signature.
这篇关于模板成员函数的实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!