问题描述
我可以创建一个模板类,在属性中存储一些值,让我以后调用一个方法来调用这个arg的函数。像这样:
I can create a template class that stores some values in a property and let me later call a method that call a function with this arg. Like this :
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();
}
但是如何使用可变参数模板我想写如下:
But how to make the same with variadic templates ? I would like to write something like :
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();
}
我知道它不会工作,因为我们不能声明一个unpacked参数的成员类型。
I know that it will not work because we cannot declare a member of unpacked parameter type.
我可以对列表的一些参数进行模式匹配,然后如果给定给定数量的参数,则调用函数,但是我想要这样做一种通用的方式。有没有一种优雅的方法来做呢?
I can do a pattern matching for some parameters of the list and then call the function if a given number of parameters is given, but I want to do it in a generic way. Is there an elegant way to do it ?
推荐答案
#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;
}
这篇关于可变参数模板类来对可变参数模板函数进行延迟调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!