Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Suy luận kiểu trong C++ (auto và decltype)

auto: kiểu biến được suy luận từ giá trị khởi tạo. decltype: trích xuất kiểu từ biểu thức.

auto type

#include <bits/stdc++.h>
using namespace std;

int main() {
    auto x = 4;
    auto y = 3.37;
    auto ptr = &x;
    cout << typeid(x).name() << endl << typeid(y).name() << endl << typeid(ptr).name() << endl;
    return 0;
}

Đầu ra

i d Pi

decltype

#include <bits/stdc++.h>
using namespace std;

int fun1() { return 10; }
char fun2() { return 'g'; }

int main() {
    decltype(fun1()) x;
    decltype(fun2()) y;
    cout << typeid(x).name() << endl << typeid(y).name() << endl;
    return 0;
}

Đầu ra

i c