C++ requires表达式返回类型概念检查如何实现取反校验?
语法限制说明
你遇到的是C++20 concept的标准语法约束:在requires表达式的复合要求{e} -> 约束中,约束位置必须是一个仅接收单个模板参数的concept,不支持直接写入带逻辑运算符的常量布尔表达式,因此-> (not IsReference)的写法不符合语法规范。
解决方案
方案1:嵌套requires子句(灵活度最高)
直接通过嵌套requires子句,配合decltype提取表达式返回类型做校验,支持任意逻辑运算组合,不需要额外定义其他concept:
template <typename T> concept HasSomeFunction = requires (T t) { t.func(); requires IsReference<decltype(t.func())>; t.anotherFunc(); requires not IsReference<decltype(t.anotherFunc())>; };
这种写法除了取反外,还可以自由组合&&、||等逻辑运算符实现多条件校验。
方案2:通用反义concept包装器(复用性更高)
如果项目中需要频繁用到concept的取反校验,可以预先定义通用的反义包装concept,后续直接在->后使用即可:
template <template <typename...> class Concept, typename... Args> concept Not = !Concept<Args...>; template <typename T> concept HasSomeFunction = requires (T t) { {t.func()} -> IsReference; {t.anotherFunc()} -> Not<IsReference>; };
内容的提问来源于stack exchange,提问作者Lessi
相关产品推荐
相关产品推荐

