ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อเข้าใจ Type Inference ใน C++ (auto และ decltype)
ในกรณีของคีย์เวิร์ด auto ประเภทของตัวแปรจะถูกอนุมานจากประเภทของ initializer ของมัน ในขณะที่ decltype ให้คุณสกัดประเภทของตัวแปรจากนิพจน์ที่เรียกใช้
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;
}
เอาต์พุต
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;
cout << typeid(y).name() << endl;
return 0;
}
เอาต์พุต
i c