MST

星途 面试题库

面试题:C++模板类派生在复杂场景下的元编程应用

设计一个模板类体系,基类`MetaBase`用于处理编译期的类型序列。从`MetaBase`派生多个模板类,如`MetaAppend`用于在类型序列末尾添加新类型,`MetaPop`用于从类型序列中移除最后一个类型,`MetaFind`用于在类型序列中查找特定类型并返回其索引(编译期确定)。请使用C++元编程技术实现这些模板类及其成员函数,确保代码的高效性和正确性,并且能够处理不同长度和类型组合的类型序列。
34.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}
  1. MetaBase基类:作为类型序列的基础模板类,用于定义类型序列。
  2. MetaAppend模板类:通过模板参数展开,将新类型NewType添加到类型序列Ts的末尾。
  3. MetaPop模板类:通过偏特化处理,移除类型序列的最后一个类型。
  4. MetaFind模板类:通过递归和条件判断,在类型序列中查找特定类型,并返回其索引。如果未找到,返回-1
  5. 测试代码:使用static_assert验证各个模板类的功能正确性。