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

时间:2018-09-09 09:11:09

标签: c++ templates variadic type-deduction

我在这里缺少有关类型推导的一些基本知识:

我正在尝试编写一个包装函数,该函数使用nullptr调用writer函数以获取所需的长度,然后调整缓冲区的大小,然后再次调用该函数(现在具有调整后的缓冲区)以获取最终输出。这些编写器函数很多,我想将调用/调整大小/调用模式归纳为可变参数模板函数。

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

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?

1 个答案:

答案 0 :(得分:4)

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

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