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

Variadic template function parameters and reference type deduction

本文关键字:参数 引用类型 变参 函数      更新时间:2023-10-16

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

我正在尝试编写一个包装函数,该函数使用 nullptr 调用编写器函数以获取所需的长度,然后调整缓冲区的大小,然后再次调用该函数,现在使用调整大小的缓冲区,以获得最终输出。有大量这样的编写器函数,我想将调用/调整大小/调用模式推广到可变参数模板函数中。

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

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&
}

我该怎么做才能让它透明地接受这两种情况?为什么它不承认传入的函数接受常量引用,并且代理的参数也是常量引用?

Args...不会推断引用类型。

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