c ++ 11:使用向量的元素调用可变函数 [英] c++11: Calling a variadic function with the elements of a vector
本文介绍了c ++ 11:使用向量的元素调用可变函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有很多关于如何用元组的元素调用可变函数的问题。
例如:
如何将一个元组扩展为可变参数模板函数的参数?
我的问题有点不同:
There are plenty of questions about how to call a variadic function with the elements of a tuple. e.g: How do I expand a tuple into variadic template function's arguments? My problem is a bit different:
我有一个函数族: / p>
I have a family of functions:
void f(int arg1);
void f(int arg1, int arg2);
...
我想要一个模板:
template<size_t Arity>
void call(std::vector<int> args) {
???
}
调用相应的 f
args [0],args [1] ...
推荐答案
这是一个工作示例:
#include <vector>
// indices machinery
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
void f(int) {}
void f(int, int) {}
// helper function because we need a way
// to deduce indices pack
template<size_t... Is>
void call_helper(const std::vector<int>& args, indices<Is...>)
{
f( args[Is]... ); // expand the indices pack
}
template<std::size_t Arity>
void call(const std::vector<int>& args)
{
if (args.size() < Arity) throw 42;
call_helper(args, typename make_indices<Arity>::type());
}
int main()
{
std::vector<int> v(2);
call<2>(v);
}
这篇关于c ++ 11:使用向量的元素调用可变函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文