7

我需要为任意元组中的每个元素调用模板或重载函数。准确地说,我需要在元组中指定元素时调用此函数。

例如。我有一个元组std::tuple<int, float> t{1, 2.0f};和一个函数

class Lambda{
public: 
   template<class T>
   void operator()(T arg){ std::cout << arg << "; "; }
};

我需要一些 struct/function Apply,如果像这样调用它Apply<Lambda, int, float>()(Lambda(), t)会产生:

1; 2.0f; 

而不是2.0f; 1;

请注意,如果将“原始”参数包传递给函数,我知道解决方案,并且我知道如何以相反的顺序对元组执行此操作。但是以下部分特化的尝试Apply失败了:

template<class Func, size_t index, class ...Components>
class ForwardsApplicator{
public:
    void operator()(Func func, const std::tuple<Components...>& t){
        func(std::get<index>(t));
        ForwardsApplicator<Func, index + 1, Components...>()(func, t);
    }
};

template<class Func, class... Components>
class ForwardsApplicator < Func, sizeof...(Components), Components... > {
public:
    void operator()(Func func, const std::tuple<Components...>& t){}
};

int main{
    ForwardsApplicator<Lambda, 0, int, float>()(Lambda{}, std::make_tuple(1, 2.0f));
}

代码已编译,但仅打印第一个参数。但是,如果我将ForwardsApplicator专业化替换为

template<class Func, class... Components>
class ForwardsApplicator < Func, 2, Components... >{...}

它可以正常工作 - 但是,当然,只适用于长度为 2 的元组。对于任意长度的元组,我该如何做——如果可能的话,优雅地?

编辑:谢谢你们的回答!这三者都非常直截了当,并从所有可能的有利位置解释了这个问题。

4

3 回答 3

9

这是一个教科书案例integer_sequence

template<class Func, class Tuple, size_t...Is>
void for_each_in_tuple(Func f, Tuple&& tuple, std::index_sequence<Is...>){
    using expander = int[];
    (void)expander { 0, ((void)f(std::get<Is>(std::forward<Tuple>(tuple))), 0)... };
}

template<class Func, class Tuple>
void for_each_in_tuple(Func f, Tuple&& tuple){
    for_each_in_tuple(f, std::forward<Tuple>(tuple),
               std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>());
}

演示

std::index_sequence和朋友都是C++14,但它是一个纯库扩展,可以很容易地用C++11实现。您可以轻松地在 SO 上找到六种实现。

于 2015-02-05T12:46:36.077 回答
6

问题是size...(Components)不能用于未知类型列表的特化Components。GCC 抱怨这个错误:

prog.cpp:16:7: error: template argument 'sizeof... (Components)' involves template parameter(s)
 class ForwardsApplicator < Func, sizeof...(Components), Components... > {
       ^

我建议采用稍微不同的方法。首先,将类型列表移动Components到 的模板参数中operator(),即:

template<class ...Components>
void operator()(Func func, const std::tuple<Components...>& t) {
    ...
}

然后,颠倒调用顺序:首先进行递归调用,然后调用 with index-1(即调用最后一个元组元素)。开始这个递归,index = sizeof...(Components)直到index = 0哪个是 noop (所以专业化有0,独立于sizeof...(Components)哪个是我开始谈论的问题)。

为了帮助调用它,添加一个用于模板参数推导的函数:

// General case (recursion)
template<class Func, size_t index>
class ForwardsApplicator{
public:
    template<class ...Components>
    void operator()(Func func, const std::tuple<Components...>& t){
        ForwardsApplicator<Func, index - 1>()(func, t);
        func(std::get<index - 1>(t));
    }
};

// Special case (stop recursion)
template<class Func>
class ForwardsApplicator<Func, 0> {
public:
    template<class ...Components>
    void operator()(Func func, const std::tuple<Components...>& t){}
};

// Helper function for template type deduction
template<class Func, class ...Components>
void apply(Func func, const std::tuple<Components...>& t) {
    ForwardsApplicator<Func, sizeof...(Components)>()(func, t);
}

然后很容易调用,不需要调用站点上的任何模板参数:

apply(Lambda{}, std::make_tuple(1, 2.0f));

现场演示

于 2015-02-05T12:36:04.237 回答
2

在模板中倒计时并不一定意味着您以相同的顺序处理元组元素。头到尾处理元组的一种简单方法是头递归(与尾递归相反):

#include <tuple>
#include <iostream>

// Our entry point is the tuple size
template<typename Tuple, std::size_t i = std::tuple_size<Tuple>::value>
struct tuple_applicator {
  template<typename Func> static void apply(Tuple &t, Func &&f) {
    // but we recurse before we process the element associated with that
    // number, reversing the order so that the front elements are processed
    // first.
    tuple_applicator<Tuple, i - 1>::apply(t, std::forward<Func>(f));
    std::forward<Func>(f)(std::get<i - 1>(t));
  }
};

// The recursion stops here.
template<typename Tuple>
struct tuple_applicator<Tuple, 0> {
  template<typename Func> static void apply(Tuple &, Func &&) { }
};

// and this is syntactical sugar
template<typename Tuple, typename Func>
void tuple_apply(Tuple &t, Func &&f) {
  tuple_applicator<Tuple>::apply(t, std::forward<Func>(f));
}

int main() {
  std::tuple<int, double> t { 1, 2.3 };

  // The generic lambda requires C++14, the rest
  // works with C++11 as well. Put your Lambda here instead.
  tuple_apply(t, [](auto x) { std::cout << x * 2 << '\n'; });
}

输出是

2
4.6
于 2015-02-05T12:29:22.683 回答