c++ - 概念中的 C++ 值评估
问题描述
如何正确评估概念声明/要求子句中的值?
考虑一个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上的实时示例。
这是我目前评估概念值的方式:
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;
推荐阅读
- python - 打印井字游戏板?
- mysql - MySQL服务器上的高CPU
- reactjs - 如何使用 d3.js 在反应应用程序中绘制三次贝塞尔曲线
- python - 如何从另一个 Python 文件运行 views.py 中的函数
- pandas - 如何将标题添加到更大数据框中的选定数据?
- scala - 为什么不能通过代码证明“不可变对象的缺点”?
- java - 运行spring boot项目时出现错误
- android - 二进制 XML 文件第 2 行:膨胀类 android.widget.RelativeLayout 时出错
- python - 如何将不同长度的字典列表转换成excel?
- python - 如何使用 Pandas 从多列中确定最大值