如何切片可变参数模板参数并使用它们?
How can I slice variadic template parameters and use them?
我对模板元编程很陌生。这就是我想做的。
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)
{
}
但是在这种情况下,"可调用"应该具有默认值才能像这样使用。
在我看来,某种辅助模板结构可能会做到这一点。
如果这件事有可能,你能给我指路吗?
提前谢谢你。
编辑我也
看过这篇文章并按照指示尝试。
成功了。但正如文中所述,我想知道是否有更标准的方法来实现这一点。
使用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++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- FFMPEG:sws_scale返回错误:切片参数 0, 2160 无效
- 切片整数参数包
- 如何切片可变参数模板参数并使用它们?
- 防止在将未引发的异常作为参数传递时在"throw e;"中切片
- 英特尔检查器 XE 2012 警告 #12367 - 将迭代器参数切片传递给 vector::erase()