[英]use of a static constexpr member function returning auto inside class
[英]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.