基本上我有一个可变参数模板函数,如下所示:
template<typename... Args>
void foo(std::string message, Args... args) {
//Some nice code
}
我现在想拥有一个存储值的结构,稍后将其用于调用此函数。我这样尝试过:
template<typename... Args>
struct Foo {
std::string message;
Args args;
Foo(std::string message, Args... args): message(message), args(args) {}
}
int main(int arg, char ** argv) {
Foo arguments("Hello, World!", 5, "LOL");
foo(arguments.message, arguments.args);
return 0;
}
但是不幸的是,这不起作用。这可以做到吗?
答案 0 :(得分:3)
在C ++中尚不允许成员包。您将不得不使用元组之类的东西,并在使用它时重新展开该包:
template<typename... Args>
struct Foo {
std::string message;
std::tuple<Args...> args;
Foo(std::string message, Args&&... args) :
message(message), args(std::forward<Args>(args)...) {}
// ^
// I added perfect forwarding to reduce copies
}
然后将元组再次转换为包,可以使用std::apply
:
std::apply(
[&](auto&&... args) {
foo(arguments.message, args...);
},
arguments.args // this is the tuple, not a pack
);