Cha*_*tas 4 c++ gcc function-pointers visual-c++ constexpr
我有一些使用 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;
}
Run Code Online (Sandbox Code Playgroud)
如果这是 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)()'
Run Code Online (Sandbox Code Playgroud)
编辑 2:
更改&bar为&foo::bar显然也可以为 clang 编译(如评论中所述。),所以我目前假设这是 GCC 中的错误。
在 C++17 之前,标准将非空指针到成员模板参数限制为
“指向成员的指针,如 [expr.unary.op] 中所述”。换句话说,这样的论证必须以精确的形式表达&A::B。
C++17 放宽了此约束以允许通用常量表达式。似乎这尚未在 GCC 中实施。
| 归档时间: |
|
| 查看次数: |
351 次 |
| 最近记录: |