阅读量:68
在 C++ 中,std::decay 是一个模板元函数,用于将给定的类型转换为其“衰减”后的类型。这通常用于从函数参数类型、引用类型或表达式类型中提取基础类型。对于自定义类型,std::decay 的行为与内置类型相同。
以下是 std::decay 的基本用法:
#include
#include
template<typename T>
void print_decayed_type() {
using decayed_type = typename std::decay::type;
std::cout<< typeid(decayed_type).name()<< std class="hljs-keyword">class MyClass {};
int main() {
print_decayed_type(); // 输出: MyClass
print_decayed_type(); // 输出: MyClass
print_decayed_type<const MyClass&>(); // 输出: MyClass
print_decayed_type(); // 输出: MyClass
print_decayed_type(); // 输出: MyClass*
print_decayed_type<const MyClass*>(); // 输出: MyClass const*
print_decayed_type3]>(); // 输出: MyClass*
print_decayed_type<MyClass(int)>(); // 输出: MyClass (*)(int)
print_decayed_type<int MyClass::*>(); // 输出: int MyClass::*
print_decayed_type<int (MyClass::*)()>(); // 输出: int (MyClass::*)()
return 0;
}
在这个例子中,我们定义了一个名为 MyClass 的自定义类型,并使用 print_decayed_type 函数模板打印其衰减后的类型。可以看到,对于自定义类型,std::decay 的行为与内置类型相同。