#include <iostream>
// 基类MetaBase,用于处理编译期的类型序列
template<typename... Ts>
struct MetaBase {};
// MetaAppend模板类,用于在类型序列末尾添加新类型
template<typename... Ts, typename NewType>
struct MetaAppend : MetaBase<Ts..., NewType> {};
// MetaPop模板类,用于从类型序列中移除最后一个类型
template<typename... Ts>
struct MetaPop;
template<>
struct MetaPop<> : MetaBase<> {};
template<typename Head, typename... Tail>
struct MetaPop<Head, Tail...> : MetaBase<Tail...> {};
// MetaFind模板类,用于在类型序列中查找特定类型并返回其索引(编译期确定)
template<typename Target, typename... Ts>
struct MetaFind;
template<typename Target>
struct MetaFind<Target> : std::integral_constant<std::size_t, -1> {};
template<typename Target, typename Head, typename... Tail>
struct MetaFind<Target, Head, Tail...>
: std::conditional_t<
std::is_same_v<Target, Head>,
std::integral_constant<std::size_t, 0>,
std::integral_constant<std::size_t, MetaFind<Target, Tail...>::value + 1>
> {};
// 测试代码
int main() {
using Types = MetaBase<int, float, double>;
// 使用MetaAppend添加新类型
using NewTypes = MetaAppend<int, float, double, char>;
static_assert(std::is_same_v<NewTypes, MetaBase<int, float, double, char>>);
// 使用MetaPop移除最后一个类型
using PoppedTypes = MetaPop<int, float, double>;
static_assert(std::is_same_v<PoppedTypes, MetaBase<int, float>>);
// 使用MetaFind查找类型
static_assert(MetaFind<float, int, float, double>::value == 1);
static_assert(MetaFind<long, int, float, double>::value == -1);
return 0;
}
MetaBase
基类:作为类型序列的基础模板类,用于定义类型序列。
MetaAppend
模板类:通过模板参数展开,将新类型NewType
添加到类型序列Ts
的末尾。
MetaPop
模板类:通过偏特化处理,移除类型序列的最后一个类型。
MetaFind
模板类:通过递归和条件判断,在类型序列中查找特定类型,并返回其索引。如果未找到,返回-1
。
- 测试代码:使用
static_assert
验证各个模板类的功能正确性。