【问题标题】:Can you interleave variadic parameters in call sites?您可以在调用站点中交错可变参数吗?
【发布时间】:2021-12-24 01:18:34
【问题描述】:

是否可以在函数调用站点内交错模板参数?

我实际上想要实现以下内容,但我不知道如何(伪代码):

template <size_t... indices, typename... Ts>
void foo(const Things *things)
{
    static_assert(sizeof...(indices) == sizeof...(Ts));
    constexpr n = sizeof...(Ts);
    bar(
      indices[0], parse<Ts[0]>(things[0]),
      indices[1], parse<Ts[1]>(things[1]),
      ...
      indices[n-1], parse<Ts[n-1]>(things[n-1]));
}

注意:我知道可以做到以下几点(伪代码):

template <size_t... indices, typename... Ts>
void foo(const Things *things)
{
    static_assert(sizeof...(indices) == sizeof...(Ts));
    constexpr n = sizeof...(Ts);
    bar(
      indices[0], indices[1], ..., indices[n-1],
      parse<Ts[0]>(things[0]),
      parse<Ts[1]>(things[1]),
      ...
      parse<Ts[n-1]>(things[n-1]));
}

我想出的部分解决方案是添加一个 swizzling 组件:

template <typename Func>
decltype(auto) swizzle()
{
    return Func();
}

template <typename Func, typename T0>
decltype(auto) swizzle(size_t i0, T0 &&t0)
{
    return Func(i0, std::forward<T0>(t0));
}

template <typename Func, typename T0, typename T1>
decltype(auto) swizzle(size_t i0, size_t i1, T0 &&t0, T1 &&t1)
{
    return Func(i0, std::forward<T0>(t0), i1, std::forward<T1>(t1));
}

但我认为我必须手动编写每个我想要考虑的案例。

【问题讨论】:

  • 有没有可能改变bar的签名?也许将这两条数据组合成一个类型?
  • @chris 我有一个不交错的工作解决方案,但对于我的用例,它会导致 API 使用稍微难看。无论解决方法如何,如果可能的话,我很想知道如何解决这个问题。我唯一的尝试是手动专门化一些“swizzling”函数包装器。缺点是我必须修复最大数量。

标签: c++ variadic-templates c++20


【解决方案1】:

像这样:

template <size_t... indices, typename... Ts>
void foo(const Things *things)
{
    std::apply([](auto...args) {
        bar(args...);
    }, std::tuple_cat(std::make_tuple(indices, parse<Ts>(*(things++)))...));
}

如果 bar 是 lambda 而不是函数模板,您可以直接将 bar 作为第一个参数传递给 std::apply。

如果你想避免复制parse&lt;Ts&gt;(*(things++))的返回值,你可以使用std::forward_as_tuple而不是std::make_tuple。

如果*(things++) 让您不舒服,一个稍微冗长的替代方法是使用std::index_sequence:

template <size_t... indices, typename... Ts>
void foo(const Things *things)
{
    [=]<auto... Is>(std::index_sequence<Is...>) {
        std::apply([](auto...args) {
            bar(args...);
        }, std::tuple_cat(std::make_tuple(indices, parse<Ts>(things[Is]))...));
    }(std::index_sequence_for<Ts...>());
}

【讨论】:

  • 非常感谢!是时候尝试一下了。对things++ 的评估顺序有任何顾虑吗?如果有,我很容易用Ts 中的每个T 对索引进行静态编码。
  • 不应该*(things++) 是things[indices]?
  • @TedLyngmo 与问题中的伪代码不同,不。 indices[n] 与 n 不同。
  • @ThomasEding 在您发布之前已经想到了这个问题,请参阅编辑
  • 好吧,我误解了这个问题。我认为indices 应该在things 上使用以选择特定的Thingss。
猜你喜欢
  • 1970-01-01
  • 2021-06-25
  • 2021-06-05
  • 2018-11-03
  • 2021-12-08
  • 2010-11-06
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
相关资源
最近更新 更多