C++ 中有没有一种方法可以创建一个模板类,该类在构造函数中接受任意数量的参数,并且可以在需要时获取这些参数?
示例:
#include <string>
template<size_t Size, typename... Types>
class Container
{
public:
Container(Types... args)
{
// add checks to see if Size = no args
}
void get(Types&... args)
{
// getter method
}
};
int main()
{
Container<3, int, double, std::string> container(10, 2.5, "smth");
int a{};
double b{};
std::string c {};
container.get(a, b, c);
// expect a = 10, b = 2.5, c = "smth"
return 0;
}
std::tuple
的形式存在:
// note: size_t parameter isn't needed, we can simply get the size using
// sizeof...(Types)
template<typename... Types>
class Container {
public:
std::tuple<Types...> stuff;
// note: in practice, this should use forwarding references and
// std::forward instead of taking everything by value
Container(Types... args) : stuff(args...) {}
void get(Types&... args) {
// std::tie creates a tuple of references, letting us
// assign all members at once
std::tie(args...) = stuff;
}
};
你可以实现一个包装
std::tuple
的容器,但它并没有真正提供std::tuple
还没有的任何实用工具,所以我们可以直接使用它:
int main() {
std::tuple<int, double, std::string> container(10, 2.5, "smth");
// not so good: decompose using three variables and std::tie
int a {};
double b {};
std::string c {};
std::tie(a, b, c) = container;
// better: use structured bindings (C++17)
auto [aa, bb, cc] = container;
}
请记住,在泛型编程之外,您最好创建自己的
struct
,并为类型和成员提供有意义的名称。
// aggregate type
struct Container {
int a;
double b;
std::string c;
};
int main() {
Container container{10, 2.5, "smth"};
// structured bindings also work for aggregate types (C++17)
auto [a, b, c] = container;
}
C++ 中有没有一种方法可以创建一个模板类,该类在构造函数中接受任意数量的参数,并且可以在需要时获取这些参数?
std::tuple
即可。是否应该将其包装到类模板中,取决于进一步的要求。
#include <tuple> // std::tuple
auto container{ std::make_tuple(10, 2.5, "smth"s) };
// Structured bindings since C++17
auto [a, b, c] = std::tuple<int, double, std::string>(container);