gpt4 book ai didi

c++ - 在 constexpr 函数中切换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:41 25 4
gpt4 key购买 nike

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

  • ...
  • branching statements if and switch

那么,在 c++14/c++17 的 constexpr 函数中是否真的可以有一个开关?而且,如果可能的话,它的语法是什么?例如,我想要这样的东西:

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;
...
}
}

最佳答案

不完全是。对于 if constexpr,您可以放心,生成的代码没有分支。此外,丢弃的语句不需要编译。这些是我认为您期望从真正的 switch constexpr 获得的保证。

class Dog;
class Snake;

#define USE_IF

template<typename Pet>
constexpr void foo(Pet pet) {
#ifdef USE_IF
// This works
if constexpr(std::is_same_v<Pet, Dog>) pet.bark();
else pet.slither();
#else
// This doesn't
switch (std::is_same_v<Pet, Dog>) {
case true: pet.bark(); break; // <== Error if Snake
case false: pet.slither(); break; // <== Error if Dog
}
#else
}

顺便说一句,对于 Baum 接受的答案,我有点挑剔,但对于实际目的来说这很好。我怀疑您会发现好的编译器会从带有 constexpr 函数的 switch-case 语句中消除逻辑上不可能的位,甚至是非 constexpr 内联函数。

关于c++ - 在 constexpr 函数中切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com