使用auto 和decltype进行类型自动推导

2022-11-08  本文已影响0人  arkliu

在 C++11 中可以使用 auto 自动推导变量的类型,还能够结合 decltype 来表示函数的返回值

PS:
使用auto声明的变量必须要进行初始化,以让编译器推导出它的实际类型,在编译时将auto占位符替换为真正的类型

auto定义变量

auto 变量名 = 变量值;

\color{red}{当变量不是指针或者引用类型时,推导的结果中不会保留 const、volatile 关键字}
\color{red}{当变量是指针或者引用类型时,推导的结果中会保留 const、volatile 关键字}

实例

int main() {
    // int
    auto i = 5;
    // double
    auto d = 6.6;
    //float
    auto f = 3.4f;


    int ii = 110;
    auto *a = ⅈ   // auto: int
    auto b = ⅈ   // auto: int *  
    auto &c = ii;   // auto: int    
    auto dd = ii;    // auto int

    int tm = 88;
    const auto first = tm;  // const int
    auto second = first;  // int 非指针或引用类型推导的结果中不会保留 const、volatile 关键字

    const auto &third = tm; // const int&
    auto& fourth = third;  // const int&
    auto* fifth = &first;  //  const int*
    return 0;
}

auto不能使用的场景

decltype使用

推导规则

int fun() {}
int * funp() {}
const int func_cint() {}

class Test
{
    public:
        int num;
        Test() {}
};

int main() {
    int a = 10;
    decltype(a) b = 99;                 // b -> int
    decltype(a+3.14) c = 52.13;         // c -> double
    decltype(a+b*c) d = 520.1314;       // d -> double

    decltype(fun()) e = 55; // 如果是函数,则推导结果为函数返回值的类型
    decltype(funp()) f = &a;
    // 对于纯右值而言,只有类类型可以携带const、volatile限定符,除此之外需要忽略掉这两个限定符, 结果为int
    decltype(func_cint()) g = 8; 

    const Test test;
    //带有括号的表达式
    decltype(test.num) first = 0;  // int
    decltype((test.num)) second = a; // const int&

    //加法表达式
    int n = 0, m = 0;
    decltype(n + m) cc = 0;  // cc是int类型
    decltype(n = n + m) dd = n; // n是左值 dd是int &类型
    return 0;
}

返回值类型后置

template<typename A, typename B>
auto add(A a, B b) -> decltype(a+b) {
    return a+b;
}

int main() {
    int a = 200;
    double b = 3.14;
    auto ret = add<int, double>(a, b);
    auto ret1 = add(a, b);
    cout << "ret = "<<ret <<"   ret1 = "<<ret1<<endl;
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读