簡體   English   中英

c ++ 11:調用帶有向量元素的可變參數函數

[英]c++11: Calling a variadic function with the elements of a vector

關於如何使用元組的元素調用可變函數存在很多問題。 例如: 如何將元組擴展為可變參數模板函數的參數? 我的問題有點不同:

我有一系列的功能:

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 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);
}

工作示例:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM