Variadic 模板函数参数和引用类型推导

Variadic template function parameters and reference type deduction

我在这里遗漏了一些关于类型推导的非常基本的东西:

我正在尝试编写一个包装函数,它调用一个带有 nullptr 的写入函数以获得所需的长度,然后调整缓冲区大小,然后再次调用该函数,现在使用调整大小的缓冲区,以获得最终输出.有很多这样的编写器函数,我想将 call/resize/call 模式概括为可变参数模板函数。

但是,当列表中的任何参数是常量引用时,我一直在尝试将函数指针传递给采用可变参数的函数,并传递可变参数:

static void val_arg(int)            { }
static void ref_arg(const int&)     { }

template <typename... Args>
static void helper(void (*fun)(Args...), Args... args)
{
    (*fun)(args...);
}

void proxy(const int& arg)
{
    helper(&val_arg, arg);  // Fine
    helper(&ref_arg, arg);  // 'void helper(void (__cdecl *)(Args...),Args...)': template parameter 'Args' is ambiguous
                            // note: could be 'const int&'
                            // note: or       'int'
}

void test()
{
    proxy(1);               // Force 1 to be const int&
}

我该怎么做才能让它透明地接受这两种情况?为什么它不承认传入的函数接受一个const ref,而代理的参数也是一个const ref?

Args... 不会推导出引用类型。

template <typename Fun, typename... Args>
static void helper(Fun fun, Args&&... args)
{
    fun(std::forward<Args>(args)...);
}