簡體   English   中英

不能在 constexpr 對象內的 constexpr 函數內使用 static_assert

[英]Cannot use static_assert inside a constexpr function inside a constexpr object

我想在編譯時檢查某個字符串是否在字符串列表中。 所以如果我在 main 中使用 static_assert,這會起作用。 但是如果我想在 constexpr 函數中使用 static_assert ,它會給我編譯錯誤:

關於為什么會出現此編譯錯誤以及如何使此編譯時檢查起作用的任何想法?

#include <array>
#include <string_view>

class ClosedList : public std::array< std::string_view, 3>
{
public:    
    constexpr bool hasValue( std::string_view  value) const
    {
        for (auto& e : *this) {
            if (value == e) {
                return true;
            }
        }
        return false;
    }

    constexpr std::string_view value(std::string_view value) const
    {
        static_assert( hasValue( value ), "value not in set");
        return value;

    }
};

int main()
{
    constexpr ClosedList myList = { "red", "green", "blue" };    
    static_assert(myList.hasValue( "red" ), "value not in set" );
    auto value = myList.value("red"); // compile error
}

如果您需要在 constexpr 方法中斷言某些內容,只需拋出。 真的。 只要 throw 表達式實際上不是在常量上下文中計算的,就明確允許在 constexpr 函數和方法中進行編譯和使用:

if (!hasValue(value)) {
    throw std::runtime_error("value not in set");
}

然后它就像你想要的那樣工作:

constexpr ClosedList myList { "a", "b", "c" };
constexpr std::string_view b = myList.value("b"); // ok
constexpr std::string_view d = myList.value("d"); // error, not a constant expression

編譯錯誤甚至指向帶有 throw 的行,因此您可以看到錯誤。

演示: https : //godbolt.org/z/da36dz

暫無
暫無

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

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