显式对象参数应用场景 ​

面试考点 ​

C++23 的 Deducing this(显式对象参数)允许把隐式的 this 指针变成显式的函数参数。面试官通过这道题考察你是否理解这个特性如何简化 CRTP、消除 const/非 const 重载的代码重复、以及实现递归 lambda。

核心概念 ​

在 C++23 之前,成员函数的 this 是隐式的,你无法控制它的类型推导。C++23 允许在成员函数的第一个参数前加 this 关键字,使其成为显式的对象参数。当使用 auto 时,编译器会推导出调用者的实际类型(包括派生类),从而实现静态多态、避免代码重复等。

基本示例 ​

cpp
#include <iostream>
#include <string>
#include <vector>
#include <type_traits>

// ============================
// 示例1:基本语法
// ============================

struct Basic {
    int value = 42;

    // 传统写法:this 是隐式的
    void print_old() const {
        std::cout << "old: " << this->value << std::endl;
    }

    // C++23 写法:this 是显式参数
    void print_new(this const Basic& self) {
        std::cout << "new: " << self.value << std::endl;
    }

    // 推导写法:self 的类型由调用者决定
    void print_deduced(this auto& self) {
        std::cout << "deduced: " << self.value << std::endl;
    }
};

void basic_demo() {
    Basic b;
    b.print_old();
    b.print_new();
    b.print_deduced();
}

// ============================
// 示例2:消除 const/非const 重载重复
// ============================

// 传统写法:需要写两份几乎相同的代码
class Container_Old {
    std::vector<int> data_ = {1, 2, 3};
public:
    // 非 const 版本
    int& at(size_t index) {
        // 边界检查等逻辑...
        return data_[index];
    }

    // const 版本:逻辑完全相同,只是返回 const 引用
    const int& at(size_t index) const {
        return data_[index];
    }
    // 代码重复!如果逻辑复杂,维护成本很高
};

// C++23 写法:一个函数搞定
class Container_New {
    std::vector<int> data_ = {1, 2, 3};
public:
    // self 的 const 性由调用者决定
    // const 对象调用 → self 是 const Container_New&,返回 const int&
    // 非 const 对象调用 → self 是 Container_New&,返回 int&
    decltype(auto) at(this auto& self, size_t index) {
        // 只写一次逻辑
        return self.data_[index];
    }
};

void dedup_demo() {
    Container_New c;
    c.at(0) = 100;  // 非 const,返回 int&,可修改
    std::cout << "修改后: " << c.at(0) << std::endl;

    const Container_New cc;
    std::cout << "const: " << cc.at(0) << std::endl;
    // cc.at(0) = 200;  // 编译错误:const int& 不可修改
}

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

// 传统 CRTP:模板参数 + static_cast
template<typename Derived>
class Printable_CRTP {
public:
    void print() const {
        // 必须 static_cast 到派生类
        const auto& self = static_cast<const Derived&>(*this);
        std::cout << "CRTP: " << self.name() << std::endl;
    }
};

class Dog_CRTP : public Printable_CRTP<Dog_CRTP> {
public:
    std::string name() const { return "Dog"; }
};

// C++23 显式对象参数:不需要模板参数
class Printable_New {
public:
    // self 自动推导为派生类类型
    void print(this auto const& self) {
        std::cout << "Deducing this: " << self.name() << std::endl;
    }
};

class Dog_New : public Printable_New {
public:
    std::string name() const { return "Dog"; }
};

class Cat_New : public Printable_New {
public:
    std::string name() const { return "Cat"; }
};

void crtp_demo() {
    Dog_CRTP d1;
    d1.print();  // CRTP: Dog

    Dog_New d2;
    d2.print();  // Deducing this: Dog

    Cat_New c;
    c.print();   // Deducing this: Cat

    // 注意区别:
    // CRTP:class Dog : public Printable<Dog>  ← 需要传自己的类型
    // 新写法:class Dog : public Printable     ← 干净的继承
}

// ============================
// 示例4:递归 lambda
// ============================

void recursive_lambda_demo() {
    // 传统方式:lambda 不能直接递归调用自己
    // 需要 std::function 或 Y-combinator

    // C++23:显式对象参数让 lambda 可以引用自己
    auto factorial = [](this auto& self, int n) -> int {
        if (n <= 1) return 1;
        return n * self(n - 1);  // 通过 self 递归
    };

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

    // 递归遍历树结构
    struct Node {
        int value;
        std::vector<Node> children;
    };

    Node tree{1, {
        {2, {{4, {}}, {5, {}}}},
        {3, {{6, {}}}}
    }};

    // 递归 lambda 遍历
    auto traverse = [](this auto& self, const Node& node) -> void {
        std::cout << node.value << " ";
        for (const auto& child : node.children) {
            self(child);
        }
    };

    traverse(tree);  // 1 2 4 5 3 6
    std::cout << std::endl;
}

// ============================
// 示例5:值类别感知(左值/右值重载)
// ============================

class Builder {
    std::string data_;
public:
    // 一个函数处理左值和右值
    // 左值调用时拷贝,右值调用时移动
    template<typename Self>
    auto build(this Self&& self) {
        if constexpr (std::is_lvalue_reference_v<Self>) {
            std::cout << "左值:拷贝 data" << std::endl;
            return self.data_;  // 拷贝
        } else {
            std::cout << "右值:移动 data" << std::endl;
            return std::move(self.data_);  // 移动
        }
    }

    Builder& set_data(std::string s) {
        data_ = std::move(s);
        return *this;
    }
};

void value_category_demo() {
    Builder b;
    b.set_data("hello");

    auto s1 = b.build();                         // 左值:拷贝
    auto s2 = Builder().set_data("world").build(); // 右值:移动
    std::cout << s1 << " " << s2 << std::endl;
}

// ============================
// 示例6:链式调用的正确返回类型
// ============================

class Chainable {
    int x_ = 0;
public:
    // 返回 self 的实际类型(可能是派生类)
    decltype(auto) set_x(this auto&& self, int x) {
        self.x_ = x;
        return std::forward<decltype(self)>(self);
    }

    void show(this auto const& self) {
        std::cout << "x = " << self.x_ << std::endl;
    }
};

void chain_demo() {
    Chainable().set_x(42).show();
}

int main() {
    std::cout << "=== 基本语法 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== 消除重复 ===" << std::endl;
    dedup_demo();

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

    std::cout << "\n=== 递归 lambda ===" << std::endl;
    recursive_lambda_demo();

    std::cout << "\n=== 值类别感知 ===" << std::endl;
    value_category_demo();

    std::cout << "\n=== 链式调用 ===" << std::endl;
    chain_demo();

    return 0;
}

显式对象参数的应用场景 ​

场景传统写法C++23 写法
const/非 const 重载写两个函数一个函数 + auto& self
CRTP 静态多态template<typename D> + static_castthis auto& self
递归 lambdastd::function 或 Y-combinatorthis auto& self
左值/右值重载写两个函数(& 和 &&)this auto&& self + if constexpr
链式调用返回类型固定返回 Base&返回 self 的实际类型

CRTP vs 显式对象参数 ​

维度CRTP显式对象参数
语法template<typename D> class Baseclass Base(普通类)
继承语法class D : Base<D>class D : Base
类型访问static_cast<D*>(this)self(自动推导)
虚函数支持不支持不支持
静态成员访问D::static_member不直接支持
编译器要求C++11+C++23

常见问题 ​

显式对象参数能用于虚函数吗?

不能。带显式对象参数的成员函数不能是 virtual,也不能是 static,不能有 cv 限定符或引用限定符。这是语言规范的限制。

显式对象参数会影响运行时性能吗?

不会。编译器对显式对象参数的处理和隐式 this 完全相同。当使用 auto 推导时,编译器在编译期确定具体类型,生成和手写代码一样的机器码。

什么时候还需要用传统 CRTP?

两种情况:1) 需要在基类中访问派生类的静态成员或类型别名(显式对象参数只能访问实例成员);2) 项目还不能使用 C++23。

适用场景 ​

  • 消除 const/非 const 成员函数的代码重复
  • 简化 CRTP 模式(静态多态、mixin)
  • 递归 lambda(替代 std::function)
  • 需要区分左值/右值调用的成员函数
  • 链式 API 需要保持派生类类型

注意事项 ​

  • 显式对象参数必须是成员函数的第一个参数
  • 不能和 virtual、static、cv/ref 限定符共用
  • 使用 this auto& 时每个调用类型会实例化一个函数版本
  • 显式对象参数函数不能通过指针调用(和普通成员函数不同)
  • 约定俗成参数名为 self(类似 Python)

总结 ​

C++23 的显式对象参数把隐式的 this 变成可推导的显式参数,解决了三大痛点:const/非 const 代码重复(一个函数搞定)、CRTP 冗长语法(不需要模板参数和 static_cast)、递归 lambda(self 参数让 lambda 能引用自己)。面试中要能演示这三个用法,对比传统写法和 C++23 写法的区别,以及说明显式对象参数不能用于虚函数的限制。