Relation between constexpr and pure functions

后端 未结 4 648
广开言路
广开言路 2020-12-11 00:16

Am I right, that:

  • Any function defined with constexpr is a pure function, and
  • Any pure function can be and must be defined with con
4条回答
  •  借酒劲吻你
    2020-12-11 01:06

    To add to what others have said, consider the following constexpr function template:

    template 
    constexpr T add(T x, T y) { return x + y; }
    

    This constexpr function template is usable in a constant expression in some cases (e.g., where T is int) but not in others (e.g., where T is a class type with an operator+ overload that is not declared constexpr).

    constexpr does not mean that the function is always usable in a constant expression, it means that the function may be usable in a constant expression.

    (There are similar examples involving nontemplate functions.)

提交回复
热议问题