C++ 编程基础(8)模版 | 8.4、类型萃取
文章目录
- 一、类型萃取
- 1、基本类型萃取
- 2、类型修饰符操作
- 3、类型关系判断
- 4、类型转换
- 5、自定义类型萃取
- 总结
前言:
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、类型修饰符操作
类型萃取还可以操作类型修饰符,如
const和volatile:
std::remove_const<T>:移除T的const修饰符。std::add_const<T>:添加const修饰符。std::remove_volatile<T>:移除volatile修饰符。std::add_volatile<T>:添加volatile修饰符。std::remove_cv<T>:移除const和volatile修饰符。std::add_cv<T>:添加const和volatile修饰符。
这些工具通过
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>:判断T和U是否为同一类型。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;
}
总结
C++中的类型萃取是模板元编程的基础工具,通过
<type_traits>头文件提供的工具,可以在编译时获取和操作类型信息,实现更灵活和高效的代码。
