我有一些代码,使用msvc可以编译,但在gcc下不能。我想知道这是msvc的非标准特性还是gcc的错误(或者更正确地说是MinGW版本v5.0.3的错误)。
请看以下代码:
template <class T>
struct object_with_func_ptr {
const T func; // An object to hold a const function pointer.
};
class foo {
public:
void bar() {} // The function I want to point to.
static constexpr auto get_bar() {
return object_with_func_ptr<decltype(&bar)>{&bar}; // A constexpr to wrap a function pointer.
}
};
template <class Func, Func Fn> struct template_using_func {};
int main() {
constexpr auto bar_obj = foo::get_bar();
// Note that this is a constexpr variable and compiles for gcc also if the template_using_func line is left out.
constexpr auto bar_func_ptr = bar_obj.func;
template_using_func<decltype(bar_func_ptr), bar_func_ptr>();
return 0;
}
如果这是msvc的非标准功能,知道是否有其他方法实现我想要做的事情会很好。
编辑:下面是MinGW生成的编译器错误:
E:\CLion\ErrorExample\main.cpp: In function 'int main()':
E:\CLion\ErrorExample\main.cpp:21:61: error: 'bar_func_ptr' is not a valid template argument for type 'void (foo::* const)()'
template_using_func<decltype(bar_func_ptr), bar_func_ptr>();
^
E:\CLion\ErrorExample\main.cpp:21:61: error: it must be a pointer-to-member of the form '&X::Y'
E:\CLion\ErrorExample\main.cpp:21:61: error: could not convert template argument 'bar_func_ptr' from 'void (foo::* const)()' to 'void (foo::* const)()'
编辑 2:
将&bar
更改为&foo::bar
显然可以使此代码适用于Clang编译器(如评论中所述)。因此,我目前认为这是GCC编译器的一个bug。
&foo::bar
。 - user7860670