Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Am I right, that:

  • Any function defined with constexpr is a pure function, and
  • Any pure function can be and must be defined with constexpr if it's not very expensive for compiler.

And if so, why arent <cmath>'s functions defined with constexpr ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

template <typename T>
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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...