【问题标题】:constexpression subscript operator of STL containersSTL容器的constexpression下标运算符
【发布时间】:2013-12-04 12:30:26
【问题描述】:
constexpr const_reference at( size_type pos ) const;

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

【问题讨论】:

    标签: c++ stl constexpr c++14


    【解决方案1】:

    函数声明中没有constexpr 参数之类的东西。 constexpr 函数调用只能在编译时求值,当且仅当该函数调用中涉及的所有参数都是常量表达式。

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

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

    【讨论】:

    • 一个非常简洁的担心是,如果std::array<T,N>::atconstexpr 上下文中进行评估,编译器必须抱怨元素超出范围,就像throw 那样at 所做的那样不是constexpr
    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      相关资源
      最近更新 更多