我有一些使用 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:更改
在 C 17 之前,该标准将非空指针到成员模板参数限制为“表示为 [expr.unary.op] 中所述的成员指针”。换句话说,这样的论点必须以确切的形式表达
C 17 放宽了此约束,允许一般常量表达式。这似乎尚未在海湾合作委员会中实施。
嗯,有一些明显的错误,比如
当我在 gcc 上测试它时,错误是 void (foo::* const)()' 到 'void (foo::* const)(),
这让我认为这是一个错误。现在,它可能是来自某些值类别的非类型模板参数的一些晦涩要求,但我希望届时会出现更清晰的错误消息。
顺便说一句,std::integral_constant
在表示编译时函数指针方面可以比你的类做得更好,除非你真的希望运行时能够改变指针指向的位置。