Skip to content

Deducing this (C++23) ​

In a Nutshell ​

Write the first parameter of a member function as this Self or this Self&&, and the compiler deduces it automatically from the value category of the calling object (lvalue/rvalue/const)—eliminating the const/non-const/rvalue-reference overload trio.

None (language feature)

Core API Cheat Sheet ​

SyntaxDescription
void func(this Self&& self)Rvalue-reference explicit object parameter
void func(this const Self& self)const lvalue reference (read-only)
void func(this Self& self)Non-const lvalue reference (mutable)
void func(this auto&& self)Perfect forwarding—one definition covers all value categories
Combined with templatestemplate<class Self> void func(this Self&& self) templated explicit object parameter
CRTP simplificationExplicit object parameters can directly replace CRTP, reducing base-class overhead

Minimal Example ​

Expand codeCollapse22 lines
C++
// Standard: C++23
#include <iostream>
#include <utility>

struct Wrapper {
    int value;

    // One function covers all three scenarios: const / non-const / rvalue
    template <typename Self>
    auto&& get(this Self&& self) {
        return std::forward<Self>(self).value;
    }
};

int main() {
    Wrapper w{42};
    const Wrapper cw{99};

    std::cout << w.get() << "\n";   // 42 (non-const lvalue)
    std::cout << cw.get() << "\n";  // 99 (const lvalue)
    std::cout << Wrapper{7}.get() << "\n"; // 7 (rvalue)
}

Embedded Applicability: Moderate ​

  • Less boilerplate: one explicit object parameter replaces the const/non-const/rvalue overload trio
  • Simplifies CRTP: types are deduced directly in the member function, eliminating base-class indirection overhead
  • Especially useful for recursive lambdas and chained-call APIs
  • A C++23 feature; compiler support is still rolling out (GCC 14.1+, Clang 18+, MSVC 19.34+)
  • Embedded toolchains have long upgrade cycles, so it is not suitable in the short term for projects that need broad compatibility

Compiler Support ​

GCCClangMSVC
14.11819.34

See Also ​


Some content is referenced from cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05