模板用法 1

使用tuple作为函数的参数

如果有一个函数和tuple:

1
2
3
4
5
int testfun(int i, int j){
return i + j;
}

std::tuple<int, int> args(1, 3);

  如果需要使用tuple作为函数的参数,要在解析tuple的成员之后分别为testfun的参数赋值,由于参数类型和返回类型已知,我们需要在编译期间完成以上工作。
首先定义一个模板函数用来包装testfun,参数1为函数指针,参数2为tuple:

1
2
3
4
5
template<typename R, typename ...Args>
R warpfun(R(*f)(Args...) , std::tuple<Args...> args) {
return Run<sizeof...(Args), R>::runfun(f, args);
}

因为需要解析tuple的参数类型,采用递归的方式解包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<int N, typename R>
struct Run{
template<typename F, typename T, typename ...Args>
static R runfun(F f, T t, Args... args) {
auto i = std::get<N - 1>(t);
return Run<N - 1, R>::runfun(f, t, i, args...);
}
};

template<typename R>
struct Run<0, R> {
template<typename F, typename T, typename ...Args>
static R runfun(F f, T t, Args... args) {
return f(args...);
}
};

然后在main中直接调用并输出:

1
std::cout << warpfun(testfun, args) << std::endl;