Switch in constexpr function
Found the following statement in Wiki:
C++11 introduced the concept of a constexpr-declared function; a function which could be executed at compile time. Their return values could be consumed by operations that require constant expressions, such as an integer template argument. However, C++11 constexpr functions could only contain a single expression that is returned (as well as static_asserts and a small number of other declarations).
C++14 relaxes these restrictions. Constexpr-declared functions may now contain the following: The conditional
if
and switch
So, Is it actually possible to have a switch in a constexpr function in c++14/c++17? And, if possible, what syntax is for that? For example, I'd like to have something like this:
enum class Terrain : std::uintmax_t {
ROAD,
SOIL,
GRASS,
MUD,
SNOW,
};
constexpr float
getStepPrice(Terrain const& terrain)
{
switch constexpr (terrain)
{
case Terrain::ROAD: return 1.0f;
...
}
}
So, Is it actually possible to have a switch in a constexpr function in c++14/c++17?
Yes.
And, if possible, what syntax is for that?
There is absolutely nothing special about the syntax, it's just a normal switch
. Like this:
constexpr int fun (int i) {
switch(i) {
case 0: return 7;
default: return 5;
}
}
int main () {
int arr[fun(3)];
}
链接地址: http://www.djcxy.com/p/68370.html
上一篇: 有没有可能知道何时constexpr真的是一个constexpr?
下一篇: 切换constexpr功能