问题描述
我有一些我想在编译时由需要某种程度验证的初始化列表初始化的类.
I have some class that I would like to be initialized at compile time by an initializer list that needs some level of validation.
我首先尝试使用static_assert,但是不会编译为静态声明的非恒定条件"错误.
I first tried static_assert but that wouldn't compile with the error "non-constant condition for static assertion"
导致此错误的最佳方法是什么?
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, e.g., 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);
}
}
或如果定义了 NDEBUG
则调用运行时函数:
or call a runtime function if NDEBUG
is defined:
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
不起作用,因为其参数必须是常量表达式,而 constexpr
函数的参数则不是常数.
static_assert
does not work because the argument thereto is required to be a constant expression, which arguments to constexpr
functions are not.
这篇关于在constexpr上下文中验证std :: initializer_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!