基本上我有一个可变的模板函数,如下所示:
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;
}
但不幸的是,这不起作用。这有点可行吗?
在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
);