簡體   English   中英

Constexpr函數指針作為模板參數MSVC vs GCC

[英]Constexpr function pointer as template argument MSVC vs GCC

我有一些代碼使用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中的一個錯誤。

在C ++ 17之前,該標准將非空指針到成員模板參數限制為“指向成員的指針,如[expr.unary.op]中所述 換句話說,這種論證必須以確切的形式&A::B來表達。

C ++ 17放寬了這個約束以允許一般的常量表達式。 看起來這還沒有在海灣合作委員會中實施。

好吧有一些明顯的錯誤,比如&bar而不是&foo::bar 如果我們解決這些問題, Clang同意MSVC ,並且當3個主要編譯器中有2個同意並且它是有意義的時候,我會選擇具有感覺的多數。

我在gcc上測試時的錯誤是void (foo::* const)()' to 'void (foo::* const)() ,這讓我覺得這是一個錯誤。 現在,它可能是來自某些值類別的非類型模板參數的一些模糊的要求,這些參數在這里沒有得到滿足,但我希望有一個更清晰的錯誤消息。

std::integral_constant說一句std::integral_constant可以更好地表示編譯時函數指針而不是類,除非你真的希望運行時能力能夠在指針指向的位置進行變換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM