有没有一种方法可以在编译时已知的索引上静态声明并且在运行时断言?例如:在编译时知道索引上的static_assert
template <class T, int Dim>
class Foo
{
T _data[Dim];
public:
const T &operator[](int idx) const
{
static_assert(idx < Dim, "out of range"); // error C2131: expression did not evaluate to a constant
return _data[idx];
}
};
int main()
{
Foo<float, 2> foo;
foo[0];
foo[1];
foo[2]; // compiler error
for (int i=0; i<5; ++i)
{
foo[i]; // run time assert when i > 1
}
return 0;
}
谢谢,更新了这个问题。 – sharvey
你可以看看__builtin_constant_p为GCC,但它不可能为你提供一个完美的解决方案,因为当你尝试做你所建议的事情时,有一些非常奇怪的GCC行为。 –
你的'foo [2]'访问不是在'constexpr'上下文中完成的,你的操作符也不是'constexpr'。你不会得到编译时错误。为了实现你的目标,使用'assert'(这将给出一个非''textexpr'调用错误,如果为false)而不是'static_assert'。 –