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

问题描述 投票:1回答:1

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

我正在尝试编写一个包装函数,该函数使用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?

c++ templates variadic type-deduction
1个回答
4
投票

Args...不会推断出参考类型。

template <typename Fun, typename... Args>
static void helper(Fun fun, Args&&... args)
{
    fun(std::forward<Args>(args)...);
}
© www.soinside.com 2019 - 2024. All rights reserved.