C++ 编程基础(8)模版 | 8.4、类型萃取

文章目录

  • 一、类型萃取
    • 1、基本类型萃取
    • 2、类型修饰符操作
    • 3、类型关系判断
    • 4、类型转换
    • 5、自定义类型萃取

前言:

C++中的类型萃取(Type Traits)是模板元编程的重要工具,用于在编译时获取和操作类型信息。类型萃取主要通过标准库中的头文件实现,提供了多种类型特性查询和操作的工具。

一、类型萃取

1、基本类型萃取

类型萃取的核心是模板类std::integral_constant,它封装了一个常量值和类型。常见的类型萃取工具包括:

  • std::is_void:判断T是否为void
  • std::is_integral:判断T是否为整数类型。
  • std::is_floating_point:判断T是否为浮点类型。
  • std::is_pointer:判断T是否为指针类型。
  • std::is_reference:判断T是否为引用类型。
  • std::is_const:判断T是否为const类型。
  • std::is_volatile:判断T是否为volatile类型。

这些工具通过value成员提供布尔值结果,例如:

#include 
#include 

int main() {
    std::cout << std::is_integral<int>::value << std::endl; // 输出 1 (true)
    std::cout << std::is_floating_point<float>::value << std::endl; // 输出 1 (true)
    std::cout << std::is_pointer<int*>::value << std::endl; // 输出 1 (true)
    return 0;
}

2、类型修饰符操作

类型萃取还可以操作类型修饰符,如constvolatile

  • std::remove_const:移除Tconst修饰符。
  • std::add_const:添加const修饰符。
  • std::remove_volatile:移除volatile修饰符。
  • std::add_volatile:添加volatile修饰符。
  • std::remove_cv:移除constvolatile修饰符。
  • std::add_cv:添加constvolatile修饰符。

这些工具通过type成员提供结果类型,例如:

#include 
#include 

int main() {
    typedef std::add_const<int>::type ConstInt;
    std::cout << std::is_const<ConstInt>::value << std::endl; // 输出 1 (true)
    return 0;
}

3、类型关系判断

类型萃取还可以判断类型间的关系:

  • std::is_same:判断TU是否为同一类型。
  • std::is_base_of:判断Base是否为Derived的基类。
  • std::is_convertible:判断From类型是否可以转换为To类型。

例如:

#include 
#include 

int main() {
    std::cout << std::is_same<int, int>::value << std::endl; // 输出 1 (true)
    std::cout << std::is_base_of<std::ios_base, std::ostream>::value << std::endl; // 输出 1 (true)
    std::cout << std::is_convertible<int, double>::value << std::endl; // 输出 1 (true)
    return 0;
}

4、类型转换

类型萃取还可以进行类型转换:

  • std::decay:模拟按值传递时的类型转换,移除引用和const/volatile修饰符,并将数组和函数转换为指针。
  • std::remove_reference:移除引用。
  • std::add_pointer:添加指针。

例如:

#include 
#include 

int main() {
    typedef std::decay<int&>::type DecayedInt;
    std::cout << std::is_same<DecayedInt, int>::value << std::endl; // 输出 1 (true)
    return 0;
}

5、自定义类型萃取

可以通过模板特化自定义类型萃取。例如,定义一个判断类型是否为指针的萃取:

#include 
#include 

template <typename T>
struct is_pointer {
    static const bool value = false;
};

template <typename T>
struct is_pointer<T*> {
    static const bool value = true;
};

int main() {
    std::cout << is_pointer<int>::value << std::endl; // 输出 0 (false)
    std::cout << is_pointer<int*>::value << std::endl; // 输出 1 (true)
    return 0;
}

你可能感兴趣的:(C++,编程基础,c++,开发语言)