[英]Why doesn't my template parameter pack work?
我一直试图让模板化的函数调用一组类似的函数来避免样板。
FooA(float a, Widget* w);
FooB(int b, Widget* w);
FooC(int c, Widget* w);
FooD(int d, int e, Widget* w);
template <typename... Args>
static void RunFoo(void (*foo)(Args..., Widget*), Args... args) {
Widget w
foo(args, &w);
}
我不明白为什么这适用于:
float a = 10;
RunFoo(FooA, a);
但每当我尝试使用多个参数时它就会失败:
int a = 10;
int b = 3;
RunFoo(FooD, a, b);
它无法编译错误:“候选模板被忽略:模板参数扣除失败”
这超出了c ++模板的功能吗?
template<class T>struct tag {using type=T;};
template<class Tag>using type_t=typename Tag::type;
template<class T>using block_deduction=type_t<tag<T>>;
template <typename... Args>
static void RunFoo(block_deduction<void(*)(Args...,Widget*)> foo, Args... args) {
Widget w
foo(args, &w);
}
你不能像Args..., Widget*
演绎Args..., Widget*
- 参数包必须是最后一般的。
这两种情况在扣除方面都是“平等的”。 block_deduction
可防止在该参数上发生扣减。 所以其他推论发生了,并且有效。
请注意,这种扣除通常是一个坏主意。 您不希望推导出一个参数,并在其他位置生成函数指针。 它很脆弱。
这可能更好:
template <class F, class... Args>
static std::result_of_t<F(Args..., Widget*)> RunFoo(F&& f, Args&&... args) {
Widget w
return std::forward<F>(f)(std::forward<Args>(args)..., &w);
}
如果要传递重载集,请将重载设置包装在重载集对象中。 std::result_of_t<?>
是C ++ 14,在C ++ 11中用typename std::result_of<?>::type
替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.