You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++23中auto(x)的实用场景有哪些?求简明示例

C++23 auto(x) 实用场景示例

一、显式构造函数场景(已有示例)

当类的拷贝构造函数被声明为explicit时,隐式拷贝会失败,auto(x)可以在不明确写出类型的前提下完成显式构造:

struct A {
    A() = default;
    explicit A(const A&) {} // 显式拷贝构造函数
};
struct B {
    A child;
};

template<class T>
void printChild(T t) {}

template<class T>
void printParent(T t) {
    // printChild(t.child); // 错误:拷贝构造函数是显式的,无法隐式转换
    printChild(A(t.child)); // 可行,但需要明确写出A的类型
    printChild(auto(t.child)); // C++23写法:自动推导类型并完成显式构造
}

int main() {
    B b;
    printParent(b);
}

二、无需显式构造函数的简化场景

当你需要生成某个对象的临时副本,但不想重复书写冗长的类型名时,auto(x)可以简化代码,让类型推导自动完成:

#include <iostream>
#include <vector>

// 接收值类型参数的函数
void process_vector(std::vector<int> vec) {
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << "\n";
}

int main() {
    const std::vector<int> data = {1, 2, 3, 4, 5};
    // 传统写法:需要重复写出std::vector<int>
    // process_vector(std::vector<int>(data));
    // C++23写法:用auto(x)自动推导类型,生成临时副本
    process_vector(auto(data));
}

这里无需显式构造函数的限制,auto(x)的核心作用是简化类型书写,尤其适合嵌套模板、长类型名的场景,让代码更简洁易读。

三、体现decay_copy优势的场景

auto(x)等价于std::decay_copy(x),会自动完成以下转换:

  • 去除引用和cv(const/volatile)限定符
  • 数组退化为指针
  • 函数退化为函数指针

相比std::decay_copy,auto(x)无需包含<utility>头文件,写法更简洁:

#include <iostream>

// 接收函数指针的函数
void invoke_func(void (*func_ptr)()) {
    func_ptr();
}

void hello() {
    std::cout << "Hello decay_copy!\n";
}

int main() {
    // 传统写法1:显式取函数地址
    // invoke_func(&hello);
    // 传统写法2:使用std::decay_copy,需要包含<utility>
    // invoke_func(std::decay_copy(hello));
    // C++23写法:auto(x)自动将函数退化为函数指针
    invoke_func(auto(hello));

    // 另一个场景:数组退化为指针
    char msg[] = "Array decay example";
    void print_str(const char* str) { std::cout << str << "\n"; }
    print_str(auto(msg)); // 自动将char[]转换为const char*
}

这个场景中,auto(x)自动处理了函数到函数指针、数组到指针的退化,同时无需手动指定转换类型,代码更简洁且无需额外头文件依赖。

内容的提问来源于stack exchange,提问作者Gonen I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:02:19