小编Car*_*ito的帖子

为什么`std :: array :: at()`没有实现为模板函数?

编辑:我忘了提到这将是在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)

c++ c++11 c++14

0
推荐指数
1
解决办法
93
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1