如何显式实例化模板函数? [英] How do I explicitly instantiate a template function?
问题描述
我有一个参数的模板函数。
我必须实例化该函数而不调用该函数意味着我必须实例化。
I have a template function with one argument. I have to instantiate that function without calling that function means explicitly I have to instantiate.
我有这个函数:
template <class T> int function_name(T a) {}
我实例化了这个函数:
I instantiated that function like this:
template int function_name<int>(int);
但我遇到了以下错误:
error: expected primary-expression before 'template'
error: expected `;' before 'template'
推荐答案
:请注意,由于代码格式问题,原始问题中的代码有些混乱。
: Note that there was some confusion regarding the code in the original question due to code formatting issues. See AnthonyHatchkins' answer for more details.
如果你真的想实例化(而不是specialize或某些)函数,请执行以下操作:
If you really want to instantiate (instead of specialize or something) the function, do this:
template <typename T> void func(T param) {} // definition
template void func<int>(int param); // explicit instantiation.
关于显式实例化和特化,似乎有很多混淆。
上面发布的代码处理显式实例化 。 specialization 的语法不同。
下面是专门化的语法:
There seems to be (a lot) of confusion regarding explicit instantiation and specialization. The code I posted above deals with explicit instantiation. The syntax for specialization is different. Here is syntax for specialization:
template <typename T> void func(T param) {} // definition
template <> void func<int>(int param) {} // specialization
注意模板后的尖括号!
Note that angle brackets after template!
这篇关于如何显式实例化模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!