constexpr和纯函数之间的关系 [英] Relation between constexpr and pure functions
问题描述
我是对的:
- 使用
constexpr
定义的任何函数a 纯功能和 - 任何纯功能都可以并且如果编译器不是很贵,则必须用
constexpr
来定义。
<如果是这样,为什么用
constexpr
定义的函数 要添加其他人的说法,请考虑以下 constexpr
函数模板:
template< typename T>
constexpr T add(T x,T y){return x + y; }
这个 constexpr
在某些情况下(例如, T
是 int
)而不是其他表达式c $ c> T 是一个具有运算符+
重载的类类型,未声明 constexpr
)。
constexpr
并不意味着函数总是在常量表达式中可用,
(有类似的示例涉及非模板函数。)
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
?
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.)
这篇关于constexpr和纯函数之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!