Gus*_*uss 0 c++ c++-concepts c++20
考虑一个概念is_red,检查给定类型是否具有color设置为 的静态 cx 成员/*undefined*/::red,其中枚举中的`/ undefined /;
template <typename T>
concept is_red = requires(T) {
{ T::color == decltype(T::color)::red };
};
Run Code Online (Sandbox Code Playgroud)
这显然是错误的,因为它只检查合成是否定义良好。
因此,这不会按预期工作:
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
Run Code Online (Sandbox Code Playgroud)
请参阅此处有关 godbolt 的实例。
这是我目前评估概念价值的方式:
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>;
};
Run Code Online (Sandbox Code Playgroud)
效果很好,但看起来有点奇怪。
也许还有另一种更干净的方法来处理 C++ 概念中的值评估?
概念的右侧可以采用任意布尔表达式。需要表达式就是这样的布尔表达式之一,但不一定是这样。可以直接写一个对比:
template <typename T>
concept is_red = T::color == decltype(T::color)::red;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |