如何在类中创建模板函数?(C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972152/
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
How to create a template function within a class? (C++)
提问by
I know it's possible to make a template function:
我知道可以创建一个模板函数:
template<typename T>
void DoSomeThing(T x){}
and it's possible to make a template class:
并且可以创建一个模板类:
template<typename T>
class Object
{
public:
int x;
};
but is it possible to make a class not within a template, and then make a function in that class a template? Ie:
但是是否可以在模板中创建一个类,然后在该类中创建一个函数作为模板?IE:
//I have no idea if this is right, this is just how I think it would look
class Object
{
public:
template<class T>
void DoX(){}
};
or something to the extent, where the class is not part of a template, but the function is?
或者在某种程度上,类不是模板的一部分,但函数是?
采纳答案by Not Sure
Your guess is the correct one. The only thing you have to remember is that the member function template definition(in addition to the declaration) should be in the header file, not the cpp, though it does nothave to be in the body of the class declaration itself.
你的猜测是正确的。你要记住的唯一的事情是,成员函数模板定义(除声明外)应在头文件,而不是CPP,虽然它并没有一定要在类声明本身的身体。
回答by none
See here: Templates, template methods,Member Templates, Member Function Templates
class Vector
{
int array[3];
template <class TVECTOR2>
void eqAdd(TVECTOR2 v2);
};
template <class TVECTOR2>
void Vector::eqAdd(TVECTOR2 a2)
{
for (int i(0); i < 3; ++i) array[i] += a2[i];
}
回答by Tobias
Yes, template member functions are perfectly legal and useful on numerous occasions.
是的,模板成员函数在很多场合都是完全合法和有用的。
The only caveat is that template member functions cannot be virtual.
唯一的警告是模板成员函数不能是虚拟的。
回答by hey
The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.
最简单的方法是将声明和定义放在同一个文件中,但这可能会导致可执行文件过大。例如
class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}
Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.
此外,可以将模板定义放在单独的文件中,即将它们放在 .cpp 和 .h 文件中。您需要做的就是将模板实例显式包含到 .cpp 文件中。例如
// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}
// .cpp file
//...
template <typename T> void Foo::some_method(T t)
{//...}
//...
template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);