Lambda 显式对象参数 ​

什么是显式对象参数 ​

C++23 引入了"显式对象参数"(Explicit Object Parameter),也叫"Deducing this"(P0847)。它允许将成员函数(包括 lambda 的 operator())中隐式的 this 参数变为显式参数,写在参数列表的第一个位置,前面加 this 关键字。

对于 lambda 来说,最直接的好处是可以实现递归 lambda——lambda 终于可以在自己的函数体中调用自己了,不再需要 std::function 或 Y 组合子这样的变通方法。

语法 ​

cpp
// 成员函数中的显式对象参数
struct Widget {
    void method(this Widget& self);              // 固定类型
    void method(this auto& self);                // 推导类型
    void method(this const Widget& self);        // const 版本
};

// Lambda 中的显式对象参数
auto lambda = [](this auto& self, int n) {
    // self 就是 lambda 自身
    self(n - 1);  // 递归调用
};

基本示例 ​

cpp
#include <iostream>
#include <string>
#include <vector>
#include <variant>
#include <functional>

// ============================
// 示例1:递归 Lambda
// ============================

void recursive_demo() {
    // C++23 之前:递归 lambda 需要 std::function(有性能开销)
    std::function<int(int)> factorial_old = [&factorial_old](int n) -> int {
        if (n <= 1) return 1;
        return n * factorial_old(n - 1);
    };

    // C++23:用显式对象参数实现递归(零开销)
    auto factorial = [](this auto& self, int n) -> int {
        if (n <= 1) return 1;
        return n * self(n - 1);  // self 就是 lambda 自身
    };

    std::cout << "5! = " << factorial(5) << std::endl;    // 120
    std::cout << "10! = " << factorial(10) << std::endl;   // 3628800

    // 斐波那契数列
    auto fibonacci = [](this auto& self, int n) -> int {
        if (n <= 1) return n;
        return self(n - 1) + self(n - 2);
    };

    std::cout << "fib(10) = " << fibonacci(10) << std::endl;  // 55
}

// ============================
// 示例2:树形结构遍历
// ============================

struct TreeNode {
    int value;
    std::vector<TreeNode> children;
};

void tree_demo() {
    TreeNode root{1, {
        {2, {{4, {}}, {5, {}}}},
        {3, {{6, {}}}},
    }};

    // 递归 lambda 遍历树
    auto count_nodes = [](this auto& self, const TreeNode& node) -> int {
        int count = 1;  // 当前节点
        for (const auto& child : node.children) {
            count += self(child);  // 递归计算子节点
        }
        return count;
    };

    std::cout << "节点数: " << count_nodes(root) << std::endl;  // 6

    // 递归打印树
    auto print_tree = [](this auto& self, const TreeNode& node, int depth) -> void {
        // 缩进
        for (int i = 0; i < depth; ++i) std::cout << "  ";
        std::cout << node.value << std::endl;

        for (const auto& child : node.children) {
            self(child, depth + 1);
        }
    };

    print_tree(root, 0);
}

// ============================
// 示例3:成员函数去重(消除 const/non-const 重载)
// ============================

class Container {
    std::vector<int> data_ = {1, 2, 3, 4, 5};

public:
    // C++23 之前:需要写两个几乎相同的重载
    // int& at(std::size_t i) { return data_[i]; }
    // const int& at(std::size_t i) const { return data_[i]; }

    // C++23:一个函数搞定所有限定版本
    auto&& at(this auto&& self, std::size_t i) {
        return std::forward<decltype(self)>(self).data_[i];
    }

    std::size_t size() const { return data_.size(); }
};

void dedup_demo() {
    Container c;
    const Container& cc = c;

    c.at(0) = 100;     // 非 const 版本,返回 int&
    std::cout << cc.at(0) << std::endl;  // const 版本,返回 const int&
}

// ============================
// 示例4:CRTP 简化
// ============================

// C++23 之前的 CRTP
template<typename Derived>
struct CounterOld {
    void increment() {
        static_cast<Derived*>(this)->value_++;
    }
};

// C++23:用显式对象参数替代 CRTP
struct CounterBase {
    int value_ = 0;

    // self 的类型由派生类决定
    void increment(this auto& self) {
        self.value_++;
    }

    void print(this const auto& self) {
        std::cout << "值: " << self.value_ << std::endl;
    }
};

struct MyCounter : CounterBase {
    // 继承的 increment 和 print 会正确地推导 self 为 MyCounter
};

void crtp_demo() {
    MyCounter mc;
    mc.increment();
    mc.increment();
    mc.increment();
    mc.print();  // 值: 3
}

// ============================
// 示例5:按值传递 this(小对象优化)
// ============================

struct SmallObject {
    int x, y;

    // 按值传递——编译器可能生成更好的代码(寄存器传参)
    int sum(this SmallObject self) {
        return self.x + self.y;
    }

    // 传统方式——通过指针传递
    int sum_traditional() const {
        return x + y;
    }
};

void by_value_demo() {
    SmallObject obj{10, 20};
    std::cout << "sum = " << obj.sum() << std::endl;  // 30
}

// ============================
// 示例6:visitor 模式与 std::variant
// ============================

void visitor_demo() {
    // 递归 lambda 实现 variant 访问
    using Expr = std::variant<int, double, std::string>;

    auto to_string = [](this auto& self, const Expr& expr) -> std::string {
        return std::visit([&self](const auto& val) -> std::string {
            using T = std::decay_t<decltype(val)>;
            if constexpr (std::is_same_v<T, int>) {
                return "int(" + std::to_string(val) + ")";
            } else if constexpr (std::is_same_v<T, double>) {
                return "double(" + std::to_string(val) + ")";
            } else {
                return "string(\"" + val + "\")";
            }
        }, expr);
    };

    Expr e1 = 42;
    Expr e2 = 3.14;
    Expr e3 = std::string("hello");

    std::cout << to_string(e1) << std::endl;
    std::cout << to_string(e2) << std::endl;
    std::cout << to_string(e3) << std::endl;
}

// ============================
// 示例7:带捕获的递归 Lambda
// ============================

void capture_recursive_demo() {
    std::vector<int> results;

    // 带捕获的递归 lambda
    auto collect_even = [&results](this auto& self, int start, int end) -> void {
        if (start > end) return;
        if (start % 2 == 0) {
            results.push_back(start);
        }
        self(start + 1, end);  // 递归
    };

    collect_even(1, 20);

    std::cout << "偶数: ";
    for (int v : results) std::cout << v << " ";
    std::cout << std::endl;
}

int main() {
    std::cout << "=== 递归 Lambda ===" << std::endl;
    recursive_demo();

    std::cout << "\n=== 树遍历 ===" << std::endl;
    tree_demo();

    std::cout << "\n=== 成员函数去重 ===" << std::endl;
    dedup_demo();

    std::cout << "\n=== CRTP 简化 ===" << std::endl;
    crtp_demo();

    std::cout << "\n=== 按值传递 this ===" << std::endl;
    by_value_demo();

    std::cout << "\n=== Visitor ===" << std::endl;
    visitor_demo();

    std::cout << "\n=== 带捕获的递归 ===" << std::endl;
    capture_recursive_demo();

    return 0;
}

显式对象参数 vs 传统隐式 this ​

方面隐式 this(传统)显式对象参数(C++23)
语法无需声明this auto& self 或 this Type& self
const 重载需要写两个函数一个模板函数自动推导
值类别重载需要四个重载一个函数配合转发
递归 lambda需要 std::function 或其他变通直接通过 self 递归
CRTP需要模板基类 + static_cast直接推导派生类类型
按值传递 this不可能可以(小对象优化)

适用场景 ​

  • 递归 lambda 函数(零开销替代 std::function)
  • 消除 const/non-const 成员函数重载(去重复代码)
  • 消除左值/右值成员函数重载
  • 简化 CRTP 模式
  • 小对象按值传递 this(寄存器传参优化)
  • 树形/图形数据结构的递归遍历

常见问题 ​

self 是固定的名字吗?

不是。self 只是约定俗成的名字,你可以用任何合法的参数名。类似地,模板参数 Self 也只是约定。

显式对象参数和 static 成员函数有什么区别?

static 成员函数没有 this 参数。显式对象参数仍然是非静态成员函数,只是把隐式的 this 变成了显式的第一个参数。

带捕获的 lambda 可以用 this auto 吗?

可以,但有限制。如果 lambda 有捕获,显式对象参数的类型必须和 lambda 闭包类型兼容(不能是不相关的类型)。

递归 lambda 用 self 和用 std::function 相比性能如何?

显式对象参数的递归 lambda 没有类型擦除开销,编译器可以完全内联。std::function 有堆分配和虚调用的开销。实际测量,递归 lambda 的性能和普通递归函数一样。

显式对象参数可以和虚函数一起用吗?

不能。虚函数不能有显式对象参数。

注意事项 ​

  • 显式对象参数必须是函数的第一个参数
  • 参数前面必须有 this 关键字
  • 虚函数不能使用显式对象参数
  • static 成员函数不能使用显式对象参数
  • 带捕获的 lambda 的显式对象参数类型必须和闭包类型相关
  • 调用时不需要传递 self 参数(编译器自动传递)

编译器支持情况 ​

编译器最低支持版本
GCC14.0
Clang18.0
MSVC19.32 (VS 2022 17.2)

总结 ​

C++23 的显式对象参数让 this 从隐式变为显式,带来了多方面的改进。对 lambda 来说,最大的收益是零开销的递归——通过 self 参数直接调用自身,不需要 std::function 的类型擦除开销。对成员函数来说,它消除了 const/non-const、左值/右值的重载重复代码,一个带 this auto&& 参数的模板成员函数就能覆盖所有情况。它还简化了 CRTP 模式——不再需要模板基类和 static_cast,直接推导派生类类型。按值传递 this 对小对象可能生成更好的代码。