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


前言:

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

一、类型萃取

1、基本类型萃取

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

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

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

#include <type_traits>
#include <iostream>

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<T>:移除Tconst修饰符。
  • std::add_const<T>:添加const修饰符。
  • std::remove_volatile<T>:移除volatile修饰符。
  • std::add_volatile<T>:添加volatile修饰符。
  • std::remove_cv<T>:移除constvolatile修饰符。
  • std::add_cv<T>:添加constvolatile修饰符。

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

#include <type_traits>
#include <iostream>

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<T, U>:判断TU是否为同一类型。
  • std::is_base_of<Base, Derived>:判断Base是否为Derived的基类。
  • std::is_convertible<From, To>:判断From类型是否可以转换为To类型。

例如:

#include <type_traits>
#include <iostream>

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

例如:

#include <type_traits>
#include <iostream>

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

5、自定义类型萃取

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

#include <type_traits>
#include <iostream>

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值