【问题标题】:How can I slice variadic template parameters and use them?如何切片可变参数模板参数并使用它们?
【发布时间】:2019-09-19 01:50:48
【问题描述】:

我对模板元编程很陌生。这就是我想做的。

template <typename... Args>
void to_be_async_func(Args&&... args)
{
   //want to use args[0...N-2] to invoke a function call
   //and args[N-1(last)] to use a handler function after the prior call.
}

int main()
{
    int a = 5;
    int b = 3;
    to_be_async_func(a, b, [](int res)
    {
       //do something with the result
       //any Callable can be passed
    });
}

一开始我也尝试过

template<typename... Args, typename Callable>
void to_be_async_func(Args&&... args, Callable op)
{

}

但是,在这种情况下,“Callable”应该具有这样使用的默认值。
在我看来,某种辅助模板结构可能会做到这一点。
如果这件事是可能的,请你给我指路吗?
提前谢谢你。

编辑
我也看过this post 并按照指示尝试过。
有效。但正如文中所说,我想知道是否有更标准的方法来实现这一点。

【问题讨论】:

  • 为什么不能更改to_be_async_func 的签名以使用Callable 作为第一个参数?
  • @Eugene 谢谢你的回复。显然,这可能是一种选择。但我想让它更像“易于使用、易于阅读”的函数调用。对我来说,如果 Callable 是最后一个参数会更有意义。 (尤其是当 Callable 是一个 lambda 表达式时。)

标签: c++ templates metaprogramming variadic-templates


【解决方案1】:

使用std::index_sequence 似乎是可行的方法:

template <typename F, typename... Args>
void to_be_async_func_first(F&& f, Args&&... args)
{
    std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
}

template <std::size_t ... Is, typename... Args>
void to_be_async_func_impl(std::index_sequence<Is...>, Args&&... args)
{
    auto&& args_tuple = std::forward_as_tuple(std::forward<Args>(args)...);
    to_be_async_func_first(std::get<sizeof...(Args) - 1>(args_tuple),
                           std::get<Is>(args_tuple)...);
}

template <typename... Args>
void to_be_async_func(Args&&... args)
{
    to_be_async_func_impl(std::make_index_sequence<sizeof...(Args) - 1>(),
                          std::forward<Args>(args)...);
}

【讨论】:

  • 确实如此!我试过这种方式,它奏效了。我将研究这段代码中使用的 c++ 语言特性。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 2016-01-22
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
相关资源
最近更新 更多