为什么`constexpr`是std :: max()的C ++ 14模板原型的一部分? [英] Why is `constexpr` part of the C++14 template prototype for `std::max()`?

查看:67
本文介绍了为什么`constexpr`是std :: max()的C ++ 14模板原型的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在cplusplus.com上,是默认的C ++ 11原型对于 std :: max()是:

Per cplusplus.com, here, the default C++11 prototype for std::max() is:

template <class T> 
const T& max(const T& a, const T& b);

在C ++ 14版本中,但是 constexpr

In the C++14 version, however constexpr was added:

template <class T> 
constexpr const T& max(const T& a, const T& b);

为什么在这里 constexpr 是什么?

Why is constexpr here and what does it add?

我认为我的问题不是此问题的重复( constexpr和const之间的区别 ),因为我要问 constexpr 的非常具体的用法,而这个问题是在问告诉我有关const和constexpr的所有知识。很难从大量的答案中找出具体用法,因为另一个问题的针对性和针对性不足,无法将答案正确地带到我的问题所在。

I think my question is not a duplicate of this one (Difference between `constexpr` and `const`), because I am asking about a very specific usage of constexpr, whereas that question is asking "tell me everything you know about const and constexpr". The specific usage is extremely hard to dig out of those massive answers because that other question isn't pointed enough and specific enough to drive the answers right to the point of my question.


  1. 此信息(此问题以及我从我的答案和此处的其他内容)在这里进入了我的答案: C中的最小值和最大值

  2. constexpr和 const

  3. std :: max()和std :: min()不是constexpr

  1. This info (this question plus what I learned from my answer and others here) just went into my answer here: MIN and MAX in C
  2. Difference between `constexpr` and `const`
  3. std::max() and std::min() not constexpr


推荐答案

这意味着该函数可以在常量表达式中使用,例如:

This means that the function can be used in constant expressions , for example:

constexpr int f = max(3, 4);

保证 f 在编译时进行评估-

guarantees that f is evaluated at compile-time.

请注意,标记为 constexpr 的函数可能同时具有编译时和运行时两种情况,具体取决于函数参数(如果是函数模板,则包含模板参数)。它必须至少具有1个编译时大小写。

Note that a function marked constexpr may have both compile-time and run-time cases depending on the function arguments (and template parameters if it is a function template). It must have at least 1 compile-time case.

自C ++ 11起,许多标准库函数都具有 constexpr 添加。

Since C++11 many standard library functions have had constexpr added .

这篇关于为什么`constexpr`是std :: max()的C ++ 14模板原型的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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