I want to check at compile time if some string is in a list of strings. So if I use static_assert in the main, this works. But if I want to use static_assert inside a constexpr function it gives me compile errors:
Any idea on why this compile error and how to make this compile time check work?
#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
}
constexprfunctions, the parameters andthisdon't count asconstexpr. The function doesn't have to be called on a compile-time constant.constexprmodifier on a function does. It causes the compiler to attempt compile-time evaluation IN A CONSTANT CONTEXT. The compiler can always do compile-time evaluation under the as-if rule, but withoutconstexprthe result cannot be used in a constant context. But as HolyBlackCat said, functions markedconstexprcan also be used outside constant context, so they can't guarantee that thestatic_assertparameter is a constant expression.