第四节 · 无限剑制 · 可变参数模板

<type_traits> 头文件提供了丰富的类型查询和转换工具,是现代 C++ 泛型编程的基础。


基本类型查询

#include <type_traits>

int main()
{
    // 检查基本类型
    cout << is_integral<int>::value << endl;        // 1
    cout << is_floating_point<double>::value << endl;  // 1
    cout << is_arithmetic<char>::value << endl;     // 1
    
    // C++17 简化语法
    cout << is_integral_v<int> << endl;             // 1
    
    // 检查指针和引用
    cout << is_pointer_v<int*> << endl;             // 1
    cout << is_reference_v<int&> << endl;           // 1
    cout << is_lvalue_reference_v<int&> << endl;    // 1
    cout << is_rvalue_reference_v<int&&> << endl;   // 1
    
    return 0;
}

复合类型查询


类型属性


类型关系


类型修改


条件类型


decay

decay 模拟值传递时的类型转换。


common_type

找出多个类型的公共类型。


实用工具


void_t 技巧


习题

  • 使用 type_traits 实现一个只接受数字类型的模板函数。

  • 编写检测类型是否有特定成员函数的模板。

  • 解释 decay_t 的作用和使用场景。

Last updated