constexpr和纯函数之间的关系 [英] Relation between constexpr and pure functions

查看:211
本文介绍了constexpr和纯函数之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是对的:




  • 使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆