存储未展开的参数包
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
);
相关文章:
- 如何在c ++中存储可变参数模板参数?
- 如何在 c++ 中存储模板参数?
- 常量参数存储在哪里 (C++)?
- 存储稍后要转发的变量参数
- 存储以前的模板参数
- C++存储带有可变参数的回调
- 将可变参数模板类存储到 std::vector 中
- 模板参数在 C++ 中存储在哪里?
- 指向(数据)成员的指针作为非类型模板参数,例如具有自动存储持续时间/无链接
- 是否可以将具有不同签名的 lambda 存储在 std::vector 中并在函数中执行它们(使用各自的参数)?
- 如何在 c++ 中存储具有值的四个参数的元组
- 我可以在类中存储构造函数的模板参数吗?
- 如何捕获函数参数并存储函数指针以供以后在 C++11 中执行?
- 在可变参数模板函数中存储参数而不使用 boost::any
- 我可以将函数的输出参数存储到unique_ptr中吗?
- 具有可变参数构造函数的类模板;将参数存储到 std::vector< std::shared_ptr<> >
- 当按引用传递参数存储在被调用方对象中,然后被调用方删除时会发生什么情况
- C++将模板参数存储为变量
- 调用带有不同数量的参数存储在数组中的函数
- 将可变参数函数模板参数存储到联合向量中的最有效方法