以下代码给出了gcc和clang的编译错误。
typedef void (*Function)();
template<class T, void (T::*M)()>
void function() {
}
template<class T>
void bind(void (T::*M)(), T * object) {
Function f = &function<T, M>;
}
struct Test {
void receive() { }
};
int main(int, char**) {
Test t;
bind(&Test::receive, &t);
return 0;
}
C语给出了更有意义的错误:
758453603/source.cpp:9:19: error: address of overloaded function 'function' does not match required type 'void ()'
Function f = &function<T, M>;
^~~~~~~~~~~~~~ 758453603/source.cpp:19:5: note: in instantiation of function template specialization 'bind<Test>' requested here
bind(&Test::receive, &t);
^ 758453603/source.cpp:4:6: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'M' void function() {
重点是传递给 bind()函数的函数指针值取决于模板参数 T ,因此可以在编译时完全解析,因此,从理论上讲,编译器具有成功编译所需的所有信息。但是,似乎编译器假定代码尝试将运行时变量用于模板类型规范并给出错误。对我来说,这表明在编译器实现或C ++规范中都存在缺陷,但是可能我错过了一些事情。