Why is `constexpr` part of the C++14 template prototype for `std::max()`?

久未见 提交于 2020-05-28 07:55:49

问题


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

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

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

Why is constexpr here and what does it add?


Note on possible duplicate

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.

Related:

  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

回答1:


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

constexpr int f = max(3, 4);

guarantees that f is evaluated at compile-time.

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.

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




回答2:


constexpr indicates to the compiler that the function's result can be calculated compile-time (given that the parameters also known at compile-time). I think this topic summarizes pretty well what you want to know: Difference between `constexpr` and `const`




回答3:


I was doing some reading and it looks like it is a modifier in this case not on the return type, but rather, on the function itself. constexpr says that max() is a constexpr function. The const T& part says that the function returns a const reference to a type T, while the constexpr part, again, modifies the function itself.

This reference (https://en.cppreference.com/w/cpp/language/constexpr) indicates through its example that a constexpr function is a function which possibly can be evaluated at compile-time, but if not at compile-time, it will be evaluated at run-time like any other normal function.

Code snippet from the above reference (asterisks added):

constN<factorial(4)> out1; // computed at ***compile time***

volatile int k = 8; // disallow optimization using volatile
std::cout << k << "! = " << factorial(k) << '\n'; // computed at ***run time***

Related:

  1. This info just went into my answer here: MIN and MAX in C


来源:https://stackoverflow.com/questions/61434693/why-is-constexpr-part-of-the-c14-template-prototype-for-stdmax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!