C++ 用std :: integer_sequence迭代
示例
从C++14开始,该标准提供了类模板
template <class T, T... Ints> class integer_sequence; template <std::size_t... Ints> using index_sequence = std::integer_sequence<std::size_t, Ints...>;
并为其生成元功能:
template <class T, T N> using make_integer_sequence = std::integer_sequence<T, /* a sequence 0, 1, 2, ..., N-1 */ >; template<std::size_t N> using make_index_sequence = make_integer_sequence<std::size_t, N>;
尽管这是C++14的标准配置,但可以使用C++11工具来实现。
我们可以使用此工具来调用带有std::tuple参数的函数(在C++17中标准化为std::apply):
namespace detail { template <class F, class Tuple, std::size_t... Is> decltype(auto) apply_impl(F&& f, Tuple&& tpl, std::index_sequence<Is...> ) { return std::forward<F>(f)(std::get<Is>(std::forward<Tuple>(tpl))...); } } template <class F, class Tuple> decltype(auto) apply(F&& f, Tuple&& tpl) { return detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(tpl), std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>{}); } //这将打印3 int f(int, char, double); auto some_args = std::make_tuple(42, 'x', 3.14); int r = apply(f, some_args); //呼叫f(42,'x',3.14)