C++ 模板特化语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8323530/
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
C++ templates specialization syntax
提问by Jan Turoň
In C++ Primer Plus (2001, Czech Translation) I have found these different template specialization syntax:
在 C++ Primer Plus(2001,捷克语翻译)中,我发现了这些不同的模板特化语法:
function template
功能模板
template <typename T> void foo(T);
specialization syntax
专业化语法
void foo(int param); // 1
void foo<int>(int param); // 2
template <> void foo<int>(int param); // 3
template <> void foo(int param); // 4
template void foo(int param); // 5
Googling a bit, I have found only No.3 examples. Is there any difference (in call, compiling, usage) among them? Are some of them obsolete/deprecated? Why not just use No.1?
谷歌搜索了一下,我只找到了第 3 个例子。它们之间有什么区别(在调用、编译、使用方面)?其中一些是否已过时/已弃用?为什么不直接使用 No.1?
回答by Nawaz
Here are comments with each syntax:
以下是每种语法的注释:
void foo(int param); //not a specialization, it is an overload
void foo<int>(int param); //ill-formed
//this form always works
template <> void foo<int>(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template <> void foo(int param); //explicit specialization
//same as above, but works only if template argument deduction is possible!
template void foo(int param); //explicit instantiation
Added by me:
由我添加:
//Notice <int>. This form always works!
template void foo<int>(int param); //explicit instantiation
//Notice <>. works only if template argument deduction is possible!
template void foo<>(int param); //explicit instantiation
From coding point of view, overload is preferred over function-template-specialization.
从编码的角度来看,重载优于函数模板特化。
So, don't specialize function template:
所以,不要专门化函数模板:
And to know the terminologies:
并了解术语:
- instantiation
- explicit instantiation
- specialization
- explicit specialization
- 实例化
- 显式实例化
- 专业化
- 明确的专业化
See this :
看到这个:
回答by gerardw
Using Visual Studio 2012, it seems to work slightly different if there's no function argument:
使用 Visual Studio 2012,如果没有函数参数,它的工作似乎略有不同:
template <typename T> T bar( );
//template int bar<int>( ) { return 0; } doesn't work
template < > int bar<int>( ) { return 0; } //does work