簡體   English   中英

靜態 constexpr 成員函數在構造函數中調用它時不返回 constexpr 值

[英]Static constexpr member function not returning a constexpr value when calling it inside the constructor

我有一個模板類,它有一個可變參數構造函數,它自己特化。 它看起來像這樣(基本上):

template<std::size_t SIZE_>
class SomeClass {
public:
    static constexpr std::size_t SIZE = SIZE_;

    template<typename T>
    static constexpr std::size_t computeTotalSize(const T& t) {
        return T::SIZE;
    }

    template <typename T, typename... Ts>
    static constexpr std::size_t computeTotalSize(const T& t, const Ts&... ts) {
        return computeTotalSize(t) + computeTotalSize(ts...);
    }

    SomeClass() = default;

    template <typename T, typename... Ts>
    SomeClass(const T& t, const Ts&... ts) {
        static_assert(computeTotalSize(t, ts...) == SOME_NUMBER, "SOME_MESSAGE");
        // some other stuff
    }
};

現在我嘗試實例化SomeClass<SOME_NUMBER>

SomeClass<SOME_NUMBER> someObject((SomeClass<1>()), (SomeClass<2>()), (SomeClass<3>()));

我收到以下錯誤:

error: constexpr variable 'totalSize' must be initialized by a constant expression
note: function parameter 't' with unknown value cannot be used in a constant expression

我希望這可以正常工作,因為我已將computeTotalSize函數聲明為constexpr並且所有參數的類型在編譯時都是已知的。

我發現如果我直接調用computeTotalSize函數,它工作正常。 例如,以下編譯:

constexpr std::size_t totalSize = SomeClass<SOME_NUMBER>::computeTotalSize((SomeClass<1>()), (SomeClass<2>()), (SomeClass<3>()));

為什么它只在第二種情況下返回一個 constexpr ? 我怎樣才能讓它在構造函數中工作?

問題是即使名為T的模板參數是一個常量表達式,但名為t的函數參數卻不是。

並且由於t不是一個常量表達式,因此它不能在 constexpr 上下文中使用,您嘗試在其中使用它,如錯誤中所述:

function parameter 't' with unknown value cannot be used in a constant expression

暫無
暫無

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

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