MST

星途 面试题库

面试题:C++可变参数模板在复杂泛型场景的运用

假设有一个类模板 `MyClass`,它需要接受任意数量不同类型的参数。使用可变参数模板为 `MyClass` 实现一个构造函数,使得它能对传入的参数进行类型安全的存储,并提供一个成员函数来打印存储的所有参数值。同时,说明如何处理不同类型参数的存储和打印逻辑。
36.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

template<typename... Args>
class MyClass {
    std::tuple<Args...> data;
public:
    MyClass(Args&&... args) : data(std::forward<Args>(args)...) {}

    void print() const {
        auto print_helper = [](const auto& arg) {
            std::cout << arg << " ";
        };
        (std::apply([&print_helper](const auto&... args) { (print_helper(args), ...); }, data), std::cout << std::endl);
    }
};

在这个实现中:

  1. 存储逻辑:使用 std::tuple 来存储不同类型的参数。std::tuple 是 C++ 标准库提供的一个固定大小的、容纳不同类型元素的容器。构造函数通过可变参数模板接收任意数量不同类型的参数,并使用 std::forward 完美转发这些参数来初始化 std::tuple
  2. 打印逻辑print 成员函数使用 std::apply 来对 std::tuple 中的每个元素应用一个打印函数。这个打印函数 print_helper 简单地将参数输出到标准输出流。(print_helper(args), ...) 是 C++17 中的折叠表达式,它会对 std::tuple 中的每个元素调用 print_helper

使用示例:

int main() {
    MyClass<int, double, std::string> obj(42, 3.14, "Hello");
    obj.print();
    return 0;
}

这个示例代码会输出 42 3.14 Hello