You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Concept替代C++成员函数的引用限定符?

能否用Concept替代成员函数的引用限定符?

结论是可以实现等效效果,但实际开发中没必要舍简求繁。

具体实现方式

首先需要定义匹配左值/右值引用的Concept:

#include <concepts>

template<typename T>
concept lvalue_concept = std::is_lvalue_reference_v<T>;

template<typename T>
concept rvalue_concept = std::is_rvalue_reference_v<T>;

然后就可以按设想编写成员函数:

struct S 
{
   void func() requires lvalue_concept<decltype(*this)> {}
   void func() requires rvalue_concept<decltype(*this)> {}
};

原理与细节

  • 当S对象以左值形式调用func时,decltype(*this)的类型是S&,会匹配带lvalue_concept约束的重载;
  • 当S对象以右值形式调用func时,decltype(*this)的类型是S&&,会匹配带rvalue_concept约束的重载;
  • 这种写法的重载决议逻辑和原生引用限定符(&/&&)完全一致,不会出现行为差异。

为什么不推荐这么写?

引用限定符是C++专门为成员函数的this值类别判断设计的语法,比用Concept更简洁直观,代码可读性更高。用Concept替代属于“用复杂工具解决简单问题”,徒增代码复杂度。

内容的提问来源于stack exchange,提问作者tommsch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:17:03