MST

星途 面试题库

面试题:C++ 模板元编程之类型序列

请使用C++ 模板元编程实现一个类型序列(type sequence),能够容纳不同类型,并提供一个模板函数来遍历这个类型序列并调用每个类型的特定成员函数。例如,类型序列中可能包含`struct A { void print() { std::cout << "A"; } };`和`struct B { void print() { std::cout << "B"; } };`,编写代码实现遍历并调用每个类型的`print`函数。
48.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <tuple>

// 定义类型序列
template <typename... Ts>
using TypeSequence = std::tuple<Ts...>;

// 辅助结构体用于遍历类型序列并调用成员函数
template <size_t Index, typename Tuple>
struct CallPrintHelper {
    static void call(const Tuple& t) {
        std::get<Index>(t).print();
        CallPrintHelper<Index - 1, Tuple>::call(t);
    }
};

template <typename Tuple>
struct CallPrintHelper<0, Tuple> {
    static void call(const Tuple& t) {
        std::get<0>(t).print();
    }
};

// 模板函数用于遍历类型序列并调用print函数
template <typename... Ts>
void callPrint(const TypeSequence<Ts...>& t) {
    CallPrintHelper<sizeof...(Ts) - 1, TypeSequence<Ts...>>::call(t);
}

// 示例类型
struct A {
    void print() { std::cout << "A"; }
};

struct B {
    void print() { std::cout << "B"; }
};

int main() {
    TypeSequence<A, B> ts;
    callPrint(ts);
    return 0;
}

代码说明:

  1. 类型序列定义:使用std::tuple来定义类型序列TypeSequencestd::tuple可以容纳不同类型的元素。
  2. 辅助结构体CallPrintHelper:用于递归遍历类型序列并调用每个类型的print函数。它通过模板参数Index来获取std::tuple中的元素并调用print函数,然后递归调用Index - 1位置的元素的print函数。
  3. 模板函数callPrint:作为对外接口,调用CallPrintHelpercall函数开始遍历和调用。
  4. 示例类型AB:包含print成员函数,用于演示调用。
  5. main函数:创建一个TypeSequence对象并调用callPrint函数来遍历并调用print函数。