与Syntax of C++ templates with function type parameters有些相关却无法打消我所有的疑虑。
如果有的话,有什么区别
template <void F(int)>
void fun1 (int a) {F(a);}
和
template <void (*F)(int)>
void fun2 (int a) {F(a);}
?
我尝试用类似的东西实例化两者
void called (int arg)
{
...
}
int main()
{
fun1(10);
fun2(20);
return 0;
}
查看 clang 3.4 和 gcc-4.8 生成的汇编代码(两者都是 -O0),我看不出有什么不同。
我知道函数名在作为参数传递时会衰减为指向其类型的指针,但无法找到明确的解释来说明在上述模板实例化过程中使用它时会发生什么。 我会说第一个模板中的“F”是可以使用 int 参数调用并且不返回任何内容的“某物”类型,而第二个模板中的“F”是指向此类“某物”的指针,并且在两种实现中,F 的使用方式与直接和通过函数指针使用函数名的方式相同。 我认为这与函数名称如何衰减为指针密切相关,但我对标准的哪一部分将其形式化感到有点困惑。
最佳答案
A non-type template-parameter of type “array of
T
” or “function returningT
” is adjusted to be of type “pointer toT
” or “pointer to function returningT
”, respectively.
[C++ 11 标准,第 14.1 节 [temp.param],第 8 段]
关于c++ - 使用函数类型与函数指针作为 C++ 模板函数参数的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21841041/