概念中的 C++ 值评估

C++ value evaluation in concepts

如何正确评估概念声明/requires 子句中的值?

考虑一个概念 is_red,它检查给定类型是否有一个 color 静态 cx 成员设置为 /*undefined*/::red,其中 `/undefined/ 在枚举中;

template <typename T>
concept is_red = requires(T) {
   { T::color == decltype(T::color)::red };
};

这显然是错误的,因为它只检查语法是否定义明确。
因此,这不会按预期工作:

namespace apple {
   enum colors{red, green, yellow };

   struct granny_smith{
      constexpr static auto color = colors::green;
   };
}

static_assert(is_red<apple::granny_smith>); // should fail, but it does not using the previous concept implementation

查看 godbolt here 上的实例。

这是我目前在概念中评估价值的方式:

template <bool condition>
using if_t = std::conditional_t<condition, std::true_type, std::false_type>;

template <typename T>
concept is_red = requires(T) {
   { if_t<(T::color == decltype(T::color)::red)> } -> std::same_as<std::true_type>;
};

效果不错,但看起来有点奇怪。

也许还有另一种更简洁的方法来处理 C++ 概念中的值评估?

一个概念的右边可以是任意的布尔表达式。 requires-expression 就是这样一个布尔表达式,但它不一定是那样。可以直接写对比:

template <typename T>
concept is_red = T::color == decltype(T::color)::red;