Код: Выделить всё
#include
#include
constexpr bool IsValid(std::string_view foo) {
return foo.length() > 2;
}
struct Wrapper {
consteval Wrapper(const char* name) : name_(name) {
// Doesn't work because name is not an integral constant expression
static_assert(IsValid(name), "Must be valid");
}
std::string_view name_;
};
int main() {
// Should compile fine
Wrapper ok { "ABC" };
// Should fail to compile
Wrapper bad { "A" };
return 0;
}
Код: Выделить всё
consteval Wrapper(const char* name) : name_(name) {
if (!IsValid(name)) {
std::abort();
}
}
Тем не менее, сообщение об ошибке довольно плохо указывает, в чем заключается ошибка для пользователей этот API. В данном случае ошибка clang:
Код: Выделить всё
:23:13: error: call to consteval function 'Wrapper::Wrapper' is not a constant expression
23 | Wrapper bad { "A" };
| ^
:11:13: note: non-constexpr function 'abort' cannot be used in a constant expression
11 | std::abort();
| ^
:23:13: note: in call to 'Wrapper(&"A"[0])'
23 | Wrapper bad { "A" };
Код: Выделить всё
void bad_name(const char*) {}
consteval Wrapper(const char* name) : name_(name) {
if (!IsValid(name)) {
bad_name("name passed to Wrapper is invalid");
}
}
Код: Выделить всё
:25:13: error: call to consteval function 'Wrapper::Wrapper' is not a constant expression
25 | Wrapper bad { "A" };
| ^
:13:13: note: non-constexpr function 'bad_name' cannot be used in a constant expression
13 | bad_name("The name supplied to Wrapper is invalid");
| ^
:25:13: note: in call to 'Wrapper(&"A"[0])'
25 | Wrapper bad { "A" };
Подробнее здесь: https://stackoverflow.com/questions/792 ... unction-wi