在调用函数时生成隐式元组

generate an implicit tuple while calling a function

本文关键字:元组 调用 函数      更新时间:2023-10-16

我想调用一个模板化函数,并将两个参数集作为元组传递。但是,在将其作为参数传递之前,调用此函数总是需要手动使用std::make_tuple构建元组。

示例:

template < typename ... OUT, typename ... IN>
void Command( std::tuple<OUT...>, std::tuple<IN...>)
{
}

int main()
{
    // Send Parameter
    uint8_t mode;
    uint16_t addr;
    // Receive Parameter
    uint16_t neighbour0;
    uint16_t neighbour1;
    Command( std::make_tuple( mode, addr ),
             std::make_tuple( neighbour0, neighbour1 ));
}

有没有机会/技巧删除函数调用中的std::make_tuple,这样我就可以写这样的东西:

Command( {mode, addr}, {neighbour0, neighbour1} );

如果符号

Command(mode, addr)(neighbour0, neighbour1);

如果是可接受的,Command()基本上可以返回一个具有绑定的第一个std::tuple<...>的函数对象,该对象将在接收其他参数时调用实际函数。也就是说,实施将与类似

template <typename... Out, typename... In>
void realCommand(std::tuple<Out...>, std::tuple<In...>);
template <typename... Out>
auto Command(Out&&... out) {
    return [&](auto&&... in){
        realCommand(std::make_tuple(std::forward<Out>(out)...),
                    std::make_tuple(std::forward<decltype(in)>(in)...));
    }
}

没有,但你可以用这样一个怪物来节省一点打字:

template<class...Ts>
auto _(Ts&&...ts)
{
    return std::make_tuple(std::forward<Ts>(ts)...);
}

Command(_(mode, addr),
        _(neighbour0, neighbour1));

通常的警告适用-仅仅因为我们可以,并不意味着我们应该…