What is consteval?

2020-03-08 07:07发布

问题:

Apparently, consteval is going to be a keyword in C++20. The cppreference page for it is currently blank. What is it going to be and how does it relate to constexpr?

回答1:

It declares immediate functions, that is, functions that must be evaluated at compile time to produce a constant. (It used to be spelled constexpr! in a previous revision of the paper.) In contrast, constexpr functions may be evaluated at compile time or run time, and need not produce a constant in all cases.

The adopted paper is P1073R3, which is not yet publicly available, but a previous revision is available and the introductory (motivation and high-level description) portion is about the same (except that the "Source Locations" section is deleted in R3).



回答2:

@geza Yes, you can overload based on consteval-ness! Consider this class:

struct MyCompileTimeInt {
  consteval MyCompileTimeInt(int v) : value(v) {}
  const int value;
};

It only has a consteval constructor, so it can only be constructed from a value known at compile-time. If I overload a function using this class, I can come up with an overload that is only considered if the integer being passed is a constant. See example at https://godbolt.org/z/_drqwB