Learning Hub Search Ctrl K

Modern C++ › C++23

Deducing this

Explicit object parameters.

Since C++23 advanced #deducing-this#explicit-object-parameter#crtp#recursive-lambda#member-functions

Explanation

Deducing this (explicit object parameters) lets a non-static member function declare its object as an ordinary first parameter, written this Self&& self. Because Self is a template parameter, it is deduced from how the function is called, covering const, non-const, lvalue and rvalue objects with one definition.

struct S {
    template <typename Self>
    auto&& get(this Self&& self) { return std::forward<Self>(self).value; }
    int value;
};

What it replaces or enables:

  1. Collapsing the 2-4 overloads (const/non-const, &/&&) of getters into one.
  2. CRTP without the pattern: a base class can call derived members by taking this Derived& self, no static_cast<Derived&>(*this) and no template base.
  3. Recursive lambdas: a lambda can call itself via its own explicit object parameter.
  4. Easier pass-by-value this (a plain this S self copies the object, useful for small types).

Example

#include <iostream>
#include <string>
#include <utility>
#include <vector>

class Buffer {
    std::vector<int> data_;
public:
    explicit Buffer(std::vector<int> d) : data_(std::move(d)) {}

    // one function replaces: int& at(size_t); const int& at(size_t) const; and rvalue versions
    template <typename Self>
    auto&& at(this Self&& self, std::size_t i) {
        return std::forward<Self>(self).data_[i];
    }
};

// CRTP replacement: the base needs no template parameter
struct Printable {
    void print(this const auto& self) {                    // 'self' is the real derived type
        std::cout << "[" << self.name() << "]\n";
    }
};

struct Dog : Printable { std::string name() const { return "dog"; } };
struct Cat : Printable { std::string name() const { return "cat"; } };

struct Counter {
    int n = 0;
    void increment(this Counter& self) { ++self.n; }       // explicit non-const object
};

int main() {
    Buffer b({10, 20, 30});
    b.at(1) = 99;                                          // non-const overload: modifiable
    const Buffer cb({1, 2, 3});
    std::cout << b.at(1) << " " << cb.at(2) << "\n";       // 99 3
    // cb.at(0) = 5;                                       // error: const Buffer gives const int&

    Dog{}.print();
    Cat{}.print();

    Counter c;
    c.increment();
    std::cout << c.n << "\n";                              // 1

    auto fib = [](this auto&& self, int n) -> int {        // a recursive lambda, no std::function
        return n < 2 ? n : self(n - 1) + self(n - 2);
    };
    std::cout << fib(10) << "\n";                          // 55
    return 0;
}

Common pitfalls

  • The explicit object parameter must be the first parameter, introduced by this; such functions can’t also be static, virtual, or have cv/ref qualifiers after the parameter list.
  • Inside, there is no implicit this: access members through self. (a common first-time compile error).
  • Forgetting std::forward<Self>(self) in a forwarding getter turns rvalue objects into lvalue results.
  • The deduced type may be a derived class, so deduction can bring in more instantiations than the old two overloads.
  • A lambda with this auto&& self can’t also use [this]; its captures behave normally, but the call operator is now a template.
  • Support: MSVC 19.32+, GCC 14+, Clang 18+.

Legacy vs modern

// C++98..20: four overloads kept in sync by hand
int&       at(size_t i) &      { return data_[i]; }
const int& at(size_t i) const& { return data_[i]; }
int&&      at(size_t i) &&     { return std::move(data_[i]); }
// C++23: one
template <class Self> auto&& at(this Self&& self, size_t i) { return std::forward<Self>(self).data_[i]; }

CRTP before C++23: template <class D> struct Base { void f() { static_cast<D*>(this)->impl(); } };. Recursive lambdas needed std::function or a Y-combinator. See Const Correctness and Virtual Functions for the compile-time vs run-time polymorphism trade-off.

Exercises

1. Why can't this const auto& self be used with self.name() for a type that lacks name()?

self is deduced as the derived class, and self.name() is looked up on it at instantiation. A type without name() fails to compile at that point (a concept can make the requirement explicit).