c++11:用向量的元素调用变差函数
c++11: Calling a variadic function with the elements of a vector
关于如何用元组的元素调用变元函数,有很多问题。例如:如何将元组扩展为可变模板函数';s的论点?我的问题有点不同:
我有一系列功能:
void f(int arg1);
void f(int arg1, int arg2);
...
我想要一个模板:
template<size_t Arity>
void call(std::vector<int> args) {
???
}
它用args[0], args[1]...
调用适当的f
下面是一个工作示例:
#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);
}
工作示例:
#include <cassert>
#include <cstddef>
#include <iostream>
#include <vector>
using namespace std;
template <size_t... I>
struct index_sequence {};
template <size_t N, size_t... I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> {};
template <size_t... I>
struct make_index_sequence<0, I...> : public index_sequence<I...> {};
int f(int a, int b) {
return a + b;
}
void f(int a, int b, int c) {
cout << "args = (" << a << ", " << b << ", " << c << ")n";
}
template <typename T, size_t... I>
auto call_(const vector<T>& vec, index_sequence<I...>)
-> decltype(f(vec[I]...)) {
return f(vec[I]...);
}
template <size_t Arity, typename T>
auto call(const vector<T>& vec)
-> decltype(call_(vec, make_index_sequence<Arity>())) {
assert(vec.size() >= Arity);
return call_(vec, make_index_sequence<Arity>());
}
int main() {
vector<int> values = {0, 1, 2, 3, 4, 5};
call<3>(values);
cout << "call<2>(values) = " << call<2>(values) << endl;
}
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?