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

ความสัมพันธ์ระหว่าง auto และ decltype ใน C++

auto และ decltype ทำหน้าที่ต่างกัน จึงไม่ map one-to-one กัน auto เป็นคีย์เวิร์ดใน C++11 ขึ้นไป ใช้สำหรับ automatic type deduction decltype type specifier ให้ชนิดของ expression ที่ระบุ ไม่เหมือน auto ที่ deduce ชนิดจากค่าที่กำหนดให้ตัวแปร decltype deduce ชนิดจาก expression ที่ส่งเข้าไป ค่าที่ decltype คืนสามารถใช้กำหนดตัวแปรอื่นได้โดยตรง

auto ปฏิบัติตามกฎ template parameter deduction อ่านเพิ่มเติมได้ที่ cppreference

ขณะที่ decltype มีกฎที่กำหนดในมาตรฐาน นี่คือข้อมูลจากมาตรฐาน:

คล้ายกับออปอเรเตอร์ sizeof operand ของ decltype ไม่ถูกประเมิน (unevaluated) อย่างไม่เป็นทางการ ชนิดที่ decltype(e) คืน deduce ดังนี้ -

  • ถ้า expression e อ้างอิงตัวแปรใน local/namespace scope, static member variable, หรือ function parameter ผลลัพธ์คือชนิดที่ประกาศของตัวแปร/พารามิเตอร์นั้น
  • ถ้า e เป็น function call หรือ overloaded operator invocation decltype(e) แทนชนิดคืนที่ประกาศของฟังก์ชันนั้น
  • มิฉะนั้น ถ้า e เป็น lvalue decltype(e) คือ T& โดย T คือชนิดของ e; ถ้า e เป็น rvalue ผลลัพธ์คือ T

Semantics เหล่านี้ออกแบบมาเพื่อตอบสนองความต้องการของ generic library writers และ直觀สำหรับมือใหม่ เพราะ return type ของ decltype ตรงกับชนิดของ object/function ตรงตามที่ประกาศในซอร์สโค้ด

ตัวอย่าง

ตัวอย่างใช้ auto และ decltype -

#include <iostream>
#include <vector>
using namespace std;
int main() {
    // ใช้ auto สำหรับ type deduction
    vector<int> arr(10);
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    // ใช้ decltype สำหรับ type deduction
    vector<int> arr2(10);
    for (decltype(arr2.begin()) it = arr2.begin(); it != arr2.end(); it++) {
        cin >> *it;
    }
    return 0;
}

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