繁体   English   中英

为什么variadic模板参数的替换失败? (在固定参数之前打包)

[英]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;
}

我怀疑这个问题与variadic模板参数在fixed 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...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM