在下面的C++代码中,bar<func_ptr>(); //does not work
这一行会导致编译错误:
#include <iostream>
using namespace std;
void foo(){
cout<<"Hello world";
};
template<void(*func)()>
void bar(){
(*func)();
}
int main() {
using fun_ptr_type= void(*)();
constexpr fun_ptr_type func_ptr=&foo;
bar<&foo>(); //works
bar<func_ptr>(); //does not work
return 0;
}
g++的输出如下:
src/main.cpp: In function ‘int main()’:
src/main.cpp:19:16: error: no matching function for call to ‘bar()’
bar<func_ptr>(); //does not work
^
src/main.cpp:10:6: note: candidate: template<void (* func)()> void bar()
void bar(){
^~~
src/main.cpp:10:6: note: template argument deduction/substitution failed:
src/main.cpp:19:16: error: ‘(fun_ptr_type)func_ptr’ is not a valid template argument for ty
pe ‘void (*)()’
bar<func_ptr>(); //does not work
^
src/main.cpp:19:16: error: it must be the address of a function with external linkage
我不理解为什么当我直接将foo
的地址作为模板参数传递时它可以工作,但是当我传递constexpr func_ptr
时,即使在编译时它确切地保留了foo
的地址,代码也无法编译。有人能解释一下吗?
编辑:我的g++版本是
$ g++ --version
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.