如何存储可变参数类型的参数
How can I store the arguments of a variadic type?
我想从动作成员函数而不是构造函数调用这个foo函数。
为此,我必须将值存储在某个地方。
我无法弄清楚执行此操作的语法。
#include <iostream>
void foo(int a, int b)
{
std::cout<<a<<b;
}
template<typename... Args>
struct Foo
{
public:
Foo(Args... args){foo(args...);}
void action(){}
private:
//Args... ?
};
int main()
{
Foo<int,int> x(1,2);
}
你可以放弃Foo
的模板化,std::function
和std::bind
:
#include <functional>
#include <iostream>
void foo(int a, int b)
{
std::cout<<a<<b;
}
struct Foo
{
public:
template<typename... Args>
Foo(Args&&... args)
// bind the arguments to foo
: func_(std::bind(foo, std::forward<Args>(args)...)) { }
// then you're able to call it later without knowing what was bound to what.
void action(){ func_(); }
private:
std::function<void()> func_;
};
int main()
{
Foo x(1,2);
x.action();
}
编辑:为了回答评论,要绑定构造函数,我会使用一个函数模板,例如
template<typename T, typename... Args> T *make_new(Args&&... args) {
return new T(std::forward<Args>(args)...);
}
然后
std::bind(make_new<SomeClass, Args...>, std::forward<Args>(args)...)
重要样式说明:请考虑绑定到 std::make_shared
或 std::make_unique
(如果可以使用 C++14(,以免费获得智能指针的好处。
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 正在将动态数组元素解析为参数?(变音符)