C++ 如何显式实例化模板函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4933056/
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 do I explicitly instantiate a template function?
提问by Balaji
I have a template function with one argument. I have to instantiate that function without calling that function means explicitly I have to instantiate.
我有一个带一个参数的模板函数。我必须在不调用该函数的情况下实例化该函数,这意味着我必须明确实例化。
I have this function:
我有这个功能:
template <class T> int function_name(T a) {}
I instantiated that function like this:
我像这样实例化了这个函数:
template int function_name<int>(int);
But I got the following errors:
但我收到以下错误:
error: expected primary-expression before 'template'
error: expected `;' before 'template'
回答by hrnt
[EDIT 2]: Note that there was some confusion regarding the code in the original question due to code formatting issues. See AnthonyHatchkins' answer for more details.
[编辑 2]:请注意,由于代码格式问题,原始问题中的代码存在一些混淆。有关更多详细信息,请参阅 AnthonyHatchkins 的回答。
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.
[EDIT] 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 specializationis 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!
注意模板后面的尖括号!
回答by Antony Hatchkins
Your code is correct.
你的代码是正确的。
The error message pertains to a place in the code that you didn't quote here.
错误消息与您未在此处引用的代码中的某个位置有关。
Update:
更新:
Original code was
原始代码是
template <class T> int function_name(T a) {}
template int function_name<int>(int);
and it was correct.
这是正确的。
But it was not quoted and thus lookedlike this:
但它没有被引用,因此看起来像这样:
template int function_name(T a) {}
template int function_name(int);
It generates the following error
它产生以下错误
a.cpp:1: error: explicit instantiation of non-template ‘int function_name'
a.cpp:1: error: expected `;' before ‘(' token
a.cpp:3: error: ‘function_name' is not a template function
which is clearly different from what OP cited.
这与 OP 引用的内容明显不同。
In this variant the second line is ok (<int>
can be omitted here), but the first line is faulty. The compiler cannot guess that T
is a template parameter.
在这个变体中,第二行没问题(<int>
这里可以省略),但第一行有问题。编译器无法猜测这T
是一个模板参数。