可变参数模板类,用于对可变参数模板函数进行延迟调用
variadic template class to make a deferred call to a variadic template function
我可以创建一个模板类,将一些值存储在属性中,稍后让我调用一个使用此参数调用函数的方法。喜欢这个:
template <typename U> void g(U u) { cout << u << endl; }
template <typename U> class C {
public:
U u;
C(U u) { this->u = u; }
void m() { g(u); }
};
int main() {
C<double> c(5.5);
c.m();
}
但是如何使用可变参数模板进行相同的操作?我想写这样的东西:
template <typename ... T> void f(T... a) { cout << "generik" << endl; }
template <typename ... T> class B {
public:
T... arg;
B(T... arg) {
this->arg = arg;
}
void m() { f(arg); }
};
int main() {
B<int,double> b(1,1.1);
b.m();
}
我知道它不起作用,因为我们无法声明解压缩参数类型的成员。
我可以对列表中的某些参数进行模式匹配,然后在给定数量的参数时调用该函数,但我想以通用方式执行此操作。有没有一种优雅的方法可以做到这一点?
您可以使用如下所示的内容:
template <typename... Ts> class B
{
public:
std::tuple<Ts...> t;
B(Ts... args)
: t(args...)
{
}
void m() { call_f(std::index_sequence_for<Ts>()); }
private:
template <std::size_t ... Is>
void call_f(std::index_sequence<Is...>)
{
f(std::get<Is>(t)...);
}
};
请注意,std::index_sequence_for
(std::make_index_sequence
)和std::index_sequence
是C++14,但可以用C++11写。
活生生的例子。
> http://ideone.com/OPl7Rz
#include <iostream>
#include <functional>
using namespace std;
template<typename... T>
void f(T... a)
{
std::initializer_list<int> {(std::cout<<a<<" ", 0)...};
}
template<typename... T>
class Defer
{
private:
std::function<void()> func;
public:
Defer(T... a) : func(std::bind(f<T...>, a...)) {}
void call() {func();}
};
int main()
{
Defer<int, float, int, const char*> d(1, 1.1, 2, "Hey");
d.call();
return 0;
}
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 从变长参数列表中提取std::string