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

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c++ - Relation between constexpr and pure functions

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

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

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...