在 C++ 中,std::decay
是一個模板元函數(shù),它可以將給定的類型轉(zhuǎn)換為其對應(yīng)的非引用、非 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;
}
在這個示例中,我們首先創(chuàng)建了一個名為 print_type
的模板函數(shù),該函數(shù)打印給定類型的名稱。然后,我們創(chuàng)建了一個整數(shù)變量 a
,并分別創(chuàng)建了一個引用 ref
和一個指針 ptr
,它們都指向 a
。接下來,我們使用 std::decay
處理這些引用和指針類型,并打印它們的結(jié)果。在這種情況下,std::decay
將引用和指針類型轉(zhuǎn)換為其對應(yīng)的非引用、非指針類型(在這里是 int
)。