【问题标题】:How can I bubble last element in the variadic templates?如何泡到Variadic模板中的最后一个元素?
【发布时间】:2018-05-07 16:32:55
【问题描述】:

我有模板函数,可以将可变参数模板作为(例如)(int, int, double)

template<class... Arg>
void
bubble(const Arg &...arg)
{ another_function(arg...); }

在函数内部,我必须使用不同的参数顺序调用(double, int, int)。我该如何实施?

【问题讨论】:

标签: c++ c++14


【解决方案1】:

使用std::index_sequence,您可以执行以下操作:

template <typename Tuple, std::size_t ... Is>
decltype(auto) bubble_impl(const Tuple& tuple, std::index_sequence<Is...>)
{
    constexpr auto size = sizeof...(Is);
    return another_function(std::get<(Is + size - 1) % size>(tuple)...);
}


template <class... Args>
decltype(auto) bubble(const Args &...args)
{
    return bubble_impl(std::tie(args...), std::index_sequence_for<Args...>{});
}

【讨论】:

  • 谢谢。但我还有一个问题。如果 another_function 已返回 value(int),如何更改此代码?
  • @Hait: 只需添加返回类型和返回:)
猜你喜欢
  • 2018-11-17
  • 2018-08-03
  • 2019-12-19
  • 2013-01-29
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
相关资源
最近更新 更多