存储未扩展的参数包
Store unexpanded parameter pack
基本上我有一个像这样的可变参数模板函数:
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
);
基本上我有一个像这样的可变参数模板函数:
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
);