【发布时间】: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