繁体   English   中英

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

[英]Variadic template function parameters and reference 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?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM