为什么这种可变模板参数的替换失败了?(在固定参数之前打包)
Why is this substitution of variadic template parameter failing ? (pack before fixed arguments)
这里有一个触发编译错误的最小示例:
#include <utility>
void foo(int, double, int)
{}
template <class... Args>
void post_forwarder(void(*fun)(Args..., int), Args&&... aArgs)
{
fun(std::forward<Args>(aArgs)..., 5);
}
int main()
{
post_forwarder(foo, 6, 6.1); // Compilation error on instantiation
return 0;
}
我怀疑这个问题与可变模板参数在固定int参数之前在函数类型中扩展的事实有关,但如果是这样的话,我找不到很好的理由。
Clang 3.6报告的错误为:
error: no matching function for call to 'post_forwarder'
note: candidate template ignored: failed template argument deduction
此处的参数推导失败:
template <class... Args>
void post_forwarder(void(*fun)(Args..., int), Args&&... aArgs)
// ^^^^^^^
对于参数包必须在末尾才能推导的一般规则。通常的解决方案是将其封装在不可推导的上下文中,这样就不会尝试进行推导:
template <typename T>
struct identity {
using type = T;
};
template <class... Args>
void post_forwarder(void(*fun)(typename identity<Args>::type..., int), Args&&... aArgs)
{
fun(std::forward<Args>(aArgs)..., 5);
}
这是有效的:
template <class F, class... Args>
void post_forwarder(F f, Args&&... aArgs) {
f(std::forward<Args>(aArgs)..., 5);
}
现场演示
编辑:重写答案:
形式Args..., int
不允许推导Args...
。
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- variadic模板中的模板参数推导失败
- 当给定默认值时,为什么此模板参数推导失败
- 模板参数推导失败,函数参数/参数不匹配
- 为什么模板参数推导失败?
- 嵌套参数包扩展失败
- 模板参数的 C++ 自动模板推导失败
- 调试模板时出现问题.专门针对 Linux GCC 7、GCC 6、GCC 5、GCC 4.9 错误构建失败:模板参数 1
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 失败,出现错误 87:参数不正确.如何判断哪个参数不正确?
- 在 g++ 6.2.1 中将参数包转发到 constructor() 失败
- 当变量和参数名称匹配时,移动语义构造失败
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 模板参数推导/替换失败,lambda作为函数指针
- 为什么在 std::transform 中使用函数对象参数失败并且需要 lambda 表达式
- C++模板参数失败,不是从错误派生的
- CreateThread参数失败
- 在CreateProcess中传递命令行参数失败