我有一些代码可以使用 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 编译(如评论中所述),所以我目前假设这是一个错误海湾合作委员会。
最佳答案
在 C++17 之前,标准将非空指针成员模板参数限制为
"a pointer to member expressed as described in [expr.unary.op]" .换句话说,这样的参数必须以 &A::B
的确切形式表达。
C++17 放宽了这个约束以允许通用常量表达式。这似乎尚未在 GCC 中实现。
关于c++ - Constexpr 函数指针作为模板参数 MSVC vs GCC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157040/