【发布时间】:2017-06-30 21:02:16
【问题描述】:
有没有办法在编译时和运行时断言已知的索引上静态断言?示例:
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;
}
【问题讨论】:
-
谢谢,更新了问题。
-
您可以查看 GCC 的 __builtin_constant_p,但它可能不会为您提供完美的解决方案,因为当您尝试执行您的建议时,GCC 会出现一些非常奇怪的行为。跨度>
-
您的
foo[2]访问未在constexpr上下文中完成,您的操作员也不是constexpr。您不会收到编译时错误。要实现您的目标,请使用assert(如果为 false,将给出非constexpr调用错误)而不是static_assert。
标签: c++ c++11 runtime compile-time static-assert