为何C++23中NotRef概念的非引用要求未触发?
问题原因分析
你的NotRef概念定义存在逻辑错误,导致约束完全失效,具体原因如下:
概念定义方式错误:你用
requires { !std::is_reference_v<T>; }来定义概念,但这种写法的本质是检查花括号内的表达式是否合法可编译,而非判断表达式的布尔值是否为真。
不管T是不是引用类型,!std::is_reference_v<T>都是一个合法的布尔常量表达式,所以这个概念对任何类型T都会返回true,自然无法限制In不能是引用。正确的概念定义方式:要基于布尔值约束类型,应该直接把布尔表达式作为概念的定义体,不需要
requires块:template <typename T> concept NotRef = !std::is_reference_v<T>;
修正后的代码示例
#include <concepts> #include <type_traits> #include <functional> template <typename T> concept NotRef = !std::is_reference_v<T>; // 修正概念定义 template <typename In, typename Out> requires NotRef<In> class SwitchType { using ConstIn = std::add_const_t<In>; public: SwitchType(const In& in) : in_{in} { } ConstIn & in_; }; int main() { int a{9}; // 此时编译会报错:约束 NotRef<int&> 不满足 SwitchType<int&, int> mytype{a}; }
额外说明
另外,你代码里的ConstIn定义在In是引用时会有隐含问题:std::add_const_t<int&>的结果还是int&(因为引用本身不能被const修饰,const限定符会被忽略),所以ConstIn &最终等价于int&,这会导致成员in_直接绑定到外部变量a,和你预期的"添加const限定"逻辑不符。
内容的提问来源于stack exchange,提问作者shan
相关产品推荐
相关产品推荐

