0

假设我有一个可变参数函数foo

template <typename... Args>
void foo(Args... args)
{
    // some work
}

我想要一个神奇的函数,它以下列方式bar将它的参数转发给:foo

说如果我打电话

bar(x, y, z);

它的效果与

foo(x.begin(), x.end(), y.begin(), y.end(), z.begin(), z.end());

如何实施bar()

template <typename... Args>
void bar(Args... args)
{
    // what should I put here?
    // foo( (args.begin(), args.end()) ... );  // doesn't work 
}
4

1 回答 1

3

如果您可以使用 C++17,请应用std::apply

template<class ...  Conts>
void bar(Conts&& ... c) {
    auto t = std::make_tuple( std::make_tuple(c.begin(),c.end())... );
    // tuple< tuple<C1.begin,C1.end>, tuple<C2.begin,C2.end>, ... >    [1]
    std::apply( [](auto&&... tuples){
            auto oneTuple = std::tuple_cat(std::forward<decltype(tuples)>(tuples)...);
            // tuple< C1.begin(), C1.end(), C2.begin(), C2.end(), ...>   [2]
            std::apply([](auto&&... its){
                foo(std::forward<decltype(its)>(its)...); /// all iterators begin/end    [3]
            }, oneTuple);
        }, t);
}
  1. tuple<begin,end>为所有条目创建元组
  2. 用于apply获取在第一步中创建的所有元组,并通过连接从它们中生成一个 - 使用tuple_cat
  3. 再次使用apply从第二步创建的元组中提取所有迭代器,将它们全部传递给foo

演示

于 2020-05-14T19:05:17.860 回答