编辑:我忘了提到这将是在constexpr没有任何动态指数的背景下.
考虑以下(非常天真)的实现:
template <class T, std::size_t N>
class array
{
// ...
template <size_type pos>
reference at()
{
static_assert(pos < N, "Index out of range.");
return m_data[pos];
}
}
Run Code Online (Sandbox Code Playgroud)
具有以下用途:
int main()
{
array<int, 5> a{1, 2, 3, 4, 5};
cout << a.at(10) << "\n"; // will throw at runtime
cout << a.at<10>() << "\n"; // static assert error; index out of range
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这有效地防止了对类型和任何令人讨厌的段错误或异常的范围访问.编译器会抛出一个错误,如下所示:
error: static assertion failed: Index out of range
static_assert(pos < …Run Code Online (Sandbox Code Playgroud)