【发布时间】:2017-07-19 11:01:02
【问题描述】:
考虑以下代码:
void func(int) {}
template<typename T> void templatedFunc(T) {}
int main()
{
void (*p)(int) = func;
bool test1 = p==func;
//bool test2 = p==templatedFunc<int>; // compilation error
bool test3 = p==&templatedFunc<int>; // but this works
}
如果您取消注释test2 行并尝试使用g++ 编译代码,您将收到以下错误:
test.cpp: In function ‘int main()’:
test.cpp:8:21: error: assuming cast to type ‘void (*)(int)’ from overloaded function [-fpermissive]
bool test2 = p==templatedFunc<int>; // compilation error
^~~~~~~~~~~~~~~~~~
我在 g++ 5.3.0 和 6.2.0 上得到了这个结果。同时用clang++ 3.6.0编译成功,没有警告。
根据此处的标准,哪个编译器是正确的 - g++,它会给出错误或 clang++,哪个没有?
如果 g++ 是正确的,那么为什么在需要显式地址运算符方面,普通函数与模板函数存在这种不对称?
【问题讨论】:
-
我的常识告诉我,clang 在这种情况下是正确的,因为一个完全专用的函数模板(或者更确切地说是一个实例化)被认为是一个正常的函数,因此应该像这样运行。
-
它是否允许您使用
void (*p)(int) = templatedFunc<int>;,或者这是否也需要&? -
顺便说一句,惯用的方法是使用
&。 -
@TripeHound 奇怪的是,g++ 在这种情况下没有抱怨。
标签: c++ templates function-pointers