我试图了解"函数类型"和"函数指针"作为模板参数之间的区别以及何时应用什么。或者,有什么区别?
简单的例子:
template <int Function(int)>
struct S1 {
//....
};
template <int (*Function)(int)>
struct S2 {
//....
};
int always42(int) {
return 42;
}
int main() {
S1<always42> s1;
S2<always42> s2;
//....
return 0;
}
还是"函数类型"会衰减为"函数指针"?
有人可以对此有所了解吗?
是的,函数类型调整为非类型模板参数的函数指针。
数组和函数类型可以写在模板声明中,但它们会自动替换为指向对象的指针和指向函数的指针。
[温度参数]/10
类型为"T 数组"或函数类型 T 的非类型模板参数将调整为"指向 T 的指针"类型。
两个模板参数都int (*)(int)
,因为int(int)
存在类型衰减。也就是说,指定为int(int)
的非类型模板参数的类型衰减为int(*)(int)
。
通过使用下面不完整的type_shower
类模板,您可以看到两个模板参数对应于相同的类型:
template<typename> struct type_shower;
template <int Function(int)>
struct S1 {
type_shower<decltype(Function)> _;
};
template <int (*Function)(int)>
struct S2 {
type_shower<decltype(Function)> _;
};
对于两者,编译器会发出相同的错误消息,其中显示了Function
的类型:
error: implicit instantiation of undefined template
'type_shower<int (*)(int)>'
type_shower<decltype(Function)> _;
请注意,如果将模板参数指定为对函数的引用,则不会发生类型衰减,即int(&)(int)
:
template <int (&Function)(int)>
struct S3 {
type_shower<decltype(Function)> _;
};
error: implicit instantiation of undefined template
'type_shower<int (&)(int)>'
type_shower<decltype(Function)> _;