deducing this是C++23引入的显式对象形参机制,用void f(this auto&& self)替代隐式this,使self完整推导调用者的cv限定和值类别;而普通成员函数的this固定为T&或const T&,无法反映右值调用。

deducing this 是什么,和普通成员函数有什么区别
deducing this 是 C++23 引入的显式对象形参(explicit object parameter)机制,它让成员函数能像普通函数一样参与模板参数推导,而不是绑定到隐式 this 指针。关键在于:你不再写 void foo(),而是写 void foo(this auto&& self) —— 此时 self 的类型会根据调用者实际类型(T&、const T&、T&&)被完整推导出来。
这解决了传统 const 重载或 template<typename Self> void foo(this Self&&) 手动转发时容易漏掉 cv-qualifier 和值类别的问题。
怎么写才能让编译器正确推导 cv 和引用类别
核心是用 auto&& 或带约束的万能引用,配合 this 说明符:
- 必须把
this放在参数列表首位,且不能加默认值或省略 - 推荐写法:
void func(this auto&& self)—— 最通用,支持所有调用方式(obj.func()、const_obj.func()、std::move(obj).func()) - 若只接受左值,可用
void func(this auto& self);若只接受右值,用void func(this auto&& self) requires std::is_rvalue_reference_v<decltype(self)> - 错误写法:
void func(this auto self)(值语义会丢失 cv 和引用信息)、void func(this const auto& self)(const写死,无法响应非 const 对象调用)
struct S {
void f(this auto&& self) {
// self 类型 = S&, const S&, S&& 之一,取决于调用上下文
static_assert(std::is_same_v<decltype(self), S&>); // 可能在非 const 左值上调用
}
};
为什么不能直接用 decltype(*this) 替代 this auto&&
因为 *this 在传统成员函数里永远是 T&(即使在 const 成员函数中也是 const T&),它不反映调用表达式的完整值类别和 cv 限定:
组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。
立即学习“C++免费学习笔记(深入)”;
-
const S s; s.f();→self是const S&,但decltype(*this)在 const 成员函数里也是const S&,看似一样?问题在右值场景: -
std::move(s).f();→self是S&&,而传统*this在任何成员函数中都不可能是&&类型(没有“右值成员函数”语法) - 更隐蔽的问题:若你试图在传统模板成员函数里用
decltype(*this)做 SFINAE,它永远不体现调用者是否为临时量,导致重载决议失效
所以 this auto&& 不是语法糖,它是唯一能捕获“调用表达式原始类型”的机制。
常见编译错误和兼容性注意点
- GCC 13+ 和 Clang 16+ 才完整支持
deducing this;MSVC 19.35+ 开始实验性支持,但需 /std:c++23 且某些约束表达式可能报错
- 常见错误信息:
error: 'this' may only appear in the declaration of a non-static member function —— 说明你把 this 写在了非首位,或用了旧标准模式
- 不能和隐式
this 混用:以下非法:void g(this auto&& self, int x) ✅,但 void h(int x, this auto&& self) ❌(this 必须第一)
- 类模板中使用时,
this auto&& 的推导独立于类模板参数,不会触发类模板实参推导(即不用于 CTAD)
deducing this;MSVC 19.35+ 开始实验性支持,但需 /std:c++23 且某些约束表达式可能报错error: 'this' may only appear in the declaration of a non-static member function —— 说明你把 this 写在了非首位,或用了旧标准模式this 混用:以下非法:void g(this auto&& self, int x) ✅,但 void h(int x, this auto&& self) ❌(this 必须第一)this auto&& 的推导独立于类模板参数,不会触发类模板实参推导(即不用于 CTAD)真正难处理的是跨重载集的一致性:一旦你用 deducing this 写了一个函数,就最好整组重载都用它,否则 const S{}.f() 可能意外匹配到非 const 版本(因传统 const 成员函数有隐式转换规则,而 this auto&& 是精确匹配)。这点很容易被忽略。

















