C++ 模板成员函数的实例化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15974080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Instantiation of template member function
提问by TiMoch
In Class.h
:
在Class.h
:
class Class {
public:
template <typename T> void function(T value);
};
In Class.cpp
:
在Class.cpp
:
template<typename T> void Class::function(T value) {
// do sth
}
In main.cpp
:
在main.cpp
:
#include "Class.h"
int main(int argc, char ** argv) {
Class a;
a.function(1);
return 0;
}
I get a linked error because Class.cpp
never instantiate void Class::function<int>(T)
.
You can explicitly instantiate a template class with :
我收到一个链接错误,因为Class.cpp
从不实例化void Class::function<int>(T)
。您可以使用以下命令显式实例化模板类:
template class std::vector<int>;
How do you explicitly instantiate a template member of a non-template class ?
如何显式实例化非模板类的模板成员?
Thanks,
谢谢,
回答by Andy Prowl
You can use the following syntax in Class.cpp
:
您可以在 中使用以下语法Class.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.
请注意,没有必要指定函数参数的名称——它们不是函数(或函数模板)签名的一部分。
回答by Didier Trosset
Have you tried with the following in Class.cpp
?
您是否尝试过以下内容Class.cpp
?
template void Class::function<int>(int value);