溫馨提示×

C++ decay中如何處理引用和指針類型

c++
小樊
99
2024-08-29 23:54:53
欄目: 編程語言

在 C++ 中,std::decay 是一個模板元函數,它可以將給定的類型轉換為其對應的非引用、非 const/volatile 類型

下面是一些示例,展示了如何使用 std::decay 處理引用和指針類型:

#include<iostream>
#include <type_traits>

template<typename T>
void print_type() {
    std::cout<< typeid(T).name()<< std::endl;
}

int main() {
    // 處理引用類型
    int a = 42;
    int& ref = a;
    using decayed_ref_type = std::decay<decltype(ref)>::type;
    print_type<decayed_ref_type>();  // 輸出: i,表示 int 類型

    // 處理指針類型
    int* ptr = &a;
    using decayed_ptr_type = std::decay<decltype(ptr)>::type;
    print_type<decayed_ptr_type>();  // 輸出: i,表示 int 類型

    return 0;
}

在這個示例中,我們首先創建了一個名為 print_type 的模板函數,該函數打印給定類型的名稱。然后,我們創建了一個整數變量 a,并分別創建了一個引用 ref 和一個指針 ptr,它們都指向 a。接下來,我們使用 std::decay 處理這些引用和指針類型,并打印它們的結果。在這種情況下,std::decay 將引用和指針類型轉換為其對應的非引用、非指針類型(在這里是 int)。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女