有沒有一種方法可以在編譯時已知的索引上靜態聲明並且在運行時斷言?例如:在編譯時知道索引上的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'。 –