c++ - Constexpr 函数指针作为模板参数 MSVC vs GCC

标签 c++ gcc visual-c++ function-pointers 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;
}

如果这是 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/

相关文章:

C++ - 动态阴影转换

c++ - 按位比较

c++ - 将十进制数截断为最接近的 4 位小数并断言

linux - 生成文件:439: recipe for target 'mysql.o' failed

c# - COM 接口(interface)从 ROT 中消失

c++ - Visual Studio 调试器的奇怪行为; "The network location cannot be reached"(ERROR_NETWORK_UNREACHABLE)

c++ - 如何获得CImg像素的位深度?

c - GNU 为 binutils、gcc 和 glib 配置选项

c++ - 带有重载 lambda 的 std::variant,用 MSVC 替代?

gcc - exit.c :(. text+0x18):使用arm-none-eabi-gcc时对 `_exit'的 undefined reference