面试题答案
一键面试#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);
}
};
在这个实现中:
- 存储逻辑:使用
std::tuple
来存储不同类型的参数。std::tuple
是 C++ 标准库提供的一个固定大小的、容纳不同类型元素的容器。构造函数通过可变参数模板接收任意数量不同类型的参数,并使用std::forward
完美转发这些参数来初始化std::tuple
。 - 打印逻辑:
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
。