Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Auto และ Decltype ใน C++ คืออะไร?

auto เป็นคีย์เวิร์ดใน C++11 ขึ้นไป ใช้สำหรับ automatic type deduction Type inference หรือ deduction หมายถึงการตรวจจับชนิดข้อมูลของ expression แบบอัตโนมัติในภาษาโปรแกรมมิ่ง เป็นคุณสมบัติในภาษาบางภาษาที่เป็น strongly statically typed ตัวอย่างเช่น คุณต้องการสร้าง iterator เพื่อวนลูป vector คุณสามารถใช้ auto ได้ -

ตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> arr(10);
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    return 0;
}

ในโปรแกรมข้างต้น it จะได้ชนิด std::vector<int>::iterator โดยอัตโนมัติ

decltype type specifier ให้ชนิดของ expression ที่ระบุ ไม่เหมือน auto ที่ deduce ชนิดจากค่าที่กำหนดให้ตัวแปร decltype deduce ชนิดจาก expression ที่ส่งเข้าไป ค่าที่ decltype คืนสามารถใช้กำหนดตัวแปรอื่นได้โดยตรง ตัวอย่าง โค้ดข้างต้นเขียนด้วย decltype ได้ดังนี้ -

ตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> arr(10);
    for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    return 0;
}

โปรดทราบว่า ชนิดที่ decltype แทนอาจแตกต่างจากชนิดที่ auto deduce คุณอ่านเพิ่มเติมได้ที่ คำอธิบาย 12 หน้า