gpt4 book ai didi

c++ - 为什么这个可变参数模板参数的替换失败了? (在固定参数之前打包)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:15 25 4
gpt4 key购买 nike

这是触发编译错误的最小示例:

#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);
}

关于c++ - 为什么这个可变参数模板参数的替换失败了? (在固定参数之前打包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com