[英]Validation of an std::initializer_list in constexpr context
I have some class that I would like to be initialized at compile time by an initializer list that needs some level of validation.我有一些类,我希望在编译时由需要某种级别验证的初始化列表初始化。
I first tried static_assert but that wouldn't compile with the error "non-constant condition for static assertion"我首先尝试了 static_assert 但这不会编译错误“静态断言的非常量条件”
What is the best way to causing a build error with this?导致构建错误的最佳方法是什么?
class foo {
public:
constexpr foo(std::initializer_list<bar> items) {
for(auto &&i: items) {
if(i == 12) // example validation logic
// fail the build
}
}
}
constexpr foo foo_list({0,1,2,3,4,5});// should succeed
constexpr foo foo_list_bad({0,1,12,4,68});// should fail to build
Use a construct that cannot be used at compile time, eg, an exception:使用在编译时无法使用的构造,例如异常:
constexpr foo(std::initializer_list<bar> items)
{
for (auto&& i : items) {
if (i == 12) {
throw std::invalid_argument{""}; // for example
}
}
}
or a false assertion if exception is disabled:如果异常被禁用,则为假断言:
constexpr foo(std::initializer_list<bar> items)
{
for (auto&& i : items) {
assert(i != 12);
}
}
or call a runtime function if NDEBUG
is defined:或者,如果定义了
NDEBUG
则调用运行时函数:
constexpr foo(std::initializer_list<bar> items)
{
for (auto&& i : items) {
if (i == 12) {
std::cerr << "Error\n";
}
}
}
A diagnostic is required if runtime-only expressions are evaluated as a part of the evaluation of a constant expression.如果仅运行时表达式作为常量表达式求值的一部分求值,则需要诊断。
static_assert
does not work because the argument thereto is required to be a constant expression, which arguments to constexpr
functions are not. static_assert
不起作用,因为它的参数需要是一个常量表达式,而constexpr
函数的参数不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.