STL 容器的 constexpression 下标运算符
constexpression subscript operator of STL containers
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
相关文章:
- 一组值的零开销下标运算符
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在继承的模板类中使用下标 [] 运算符
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- c++下标运算符到下级类向量
- 数组下标运算符 ([ ]) 对数组有什么作用?
- 双标具有下标运算符的原因是什么?
- 基成员的重载下标运算符
- SFINAE 为什么我没有检测到 std::vector 的下标运算符?
- 如何重载下标运算符以返回可以是左值的可选值?
- C++下标运算符的继承规则
- 使用带有下标运算符的赋值运算符将值分配给 std::map
- 如何从重载的下标 [] 运算符返回 std::unique_ptr&?
- 为下标运算符和函数调用运算符提供默认参数
- C++ 下标运算符
- 将类实例作为指针传递,并在此指针上使用过载的下标运算符
- 如何为模板类的下标运算符
- 如何在提升 lambda 中使用下标运算符
- "飞机"不提供下标运算符是什么意思"