STL 容器的 constexpression 下标运算符

constexpression subscript operator of STL containers

本文关键字:下标 运算符 constexpression STL      更新时间:2023-10-16
constexpr const_reference at( size_type pos ) const;

STL 容器访问器的这种重载如何使用非 constexpr 参数?这种重载的经典用例是什么?

函数声明中没有constexpr参数这样的东西。仅当且仅当该函数调用中涉及的所有参数都是常量表达式时,才能在编译时计算constexpr函数调用。

话虽如此,必须在编译时计算constexpr函数的唯一情况是使用它来计算模板参数。

您给出的示例至少有一个用例是 std::array::at .

STL 容器访问器的这种重载如何使用非 constexpr 参数?

声明一个函数constexpr意味着,如果它的所有参数都使用常量表达式调用它,那么结果也是一个常量表达式。

它仍然可以用非常量参数调用;你不能将结果用作常量表达式。

这种重载的经典用例是什么?

从合适的容器中获取编译时常量,例如:

constexpr std::array<int,5> values {{2,3,5,7,11}};
template <int n> void do_stuff();  // needs a compile-time constant
do_stuff<values.at(3)>();          // provide a compile-time constant