优秀的编程知识分享平台

网站首页 > 技术文章 正文

C++(一):auto使用中的那些坑(c++ decltype auto)

nanyue 2024-07-22 14:08:51 技术文章 10 ℃

auto遇上const、volatile和&限定符

auto 不会保留原有变量的const、volatile和&限定符,如果需要保留,有两种方法: 一种是声明为decltype(auto); 另一种是显示的添加限定符,例如const auto&。

int  a = 10;
    int& a1 = a;
    // the type of a2 is int
    auto a2 = a1;
    // the type of a3 is int&
    decltype(auto) a3 = a1;
    std::cout << "The type of a2 : " << type_to_string<decltype(a2)>() << std::endl;
    std::cout << "The type of a3 : " << type_to_string<decltype(a3)>() << std::endl;

    int  b = 10;
    const int& b1 = b;
    // the type of b2 is int
    auto b2 = b1;
    // the type of b3 is const int&
    decltype(auto) b3 = b1;
    std::cout << "The type of b2 : " << type_to_string<decltype(b2)>() << std::endl;
    std::cout << "The type of b3 : " << type_to_string<decltype(b3)>() << std::endl;

输出:

The type of a2 : int
The type of a3 : int&
The type of b2 : int
The type of b3 : const int&

auto遇上匿名对象

struct {
    int age;
} person;
// 可以对匿名对象使用auto
auto p = person;
auto f = [&](int lhd, int rhd) { lhd + rhd; };
std::cout << "The type of p : " << type_to_string<decltype(p)>() << std::endl;
std::cout << "The type of f : " << type_to_string<decltype(f)>() << std::endl;

输出:

The type of p : struct <unnamed-type-person>
The type of f : class main::<lambda_1>

auto遇上原子变量

不能对不能移动的类型使用auto,例如

// auto int_atomic = std::atomic<int>(42); //error C2065: “int_atomic”: 未声明的标识符

auto遇上multi-word类型

不能对multi-word类型,例如long long, long double,使用auto

// auto l1 = long long{ 42 };   // error gcc11 : error: expected primary-expression before 'long' , vs2022 : error C2065: “l1”: 未声明的标识符
    // auto d1 = long double{};     // error gcc11 : error: expected primary-expression before 'long'
    using llong = long long;
    auto l2 = llong{ 42 };       // gcc11 : long long int
    auto l3 = 42LL;
    // std::cout << "The type of l1 : " << type_to_string<decltype(l1)>() << std::endl;
    // std::cout << "The type of d1 : " << type_to_string<decltype(d1)>() << std::endl;
    std::cout << "The type of l2 : " << type_to_string<decltype(l2)>() << std::endl;
    std::cout << "The type of l3 : " << type_to_string<decltype(l3)>() << std::endl;

输出:

The type of l2 : __int64
The type of l3 : __int64

auto遇上lambda

add可以对任意对象进行相加操作,只要它定义了 operator+

auto add = [] (auto const a, auto const b) { return a + b; };
    auto res1 = add("hello"s, "world"s);
    decltype(auto) res2 = add("hello"s, "world"s);
    std::cout << "The type of res1 : " << type_to_string<decltype(res1)>() << std::endl;
    std::cout << "The type of res2 : " << type_to_string<decltype(res2)>() << std::endl;

输出:

The type of res1 : class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
The type of res2 : class std::basic_string<char,struct std::char_traits<char>,class std:
最近发表
标签列表