可变参数模板函数参数和引用类型推导
Variadic template function parameters and reference type deduction
我在这里缺少一些关于类型推导的非常基本的东西:
我正在尝试编写一个包装函数,该函数使用 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)...);
}
相关文章:
- 通过引用传递参数时C++类型转换
- 可变参数模板函数参数和引用类型推导
- 隐式可转换参数,但属于引用类型
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- C++ 引用类型作为递归函数参数
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 为什么模板引用类型不能用作模板类型别名参数?
- 模板默认参数将丢失其引用类型
- 为什么右值引用类型的模板参数可以绑定到左值类型?
- 当将对象传递给具有参数作为引用类型的函数以及当其类对象类型时,会得到不同的输出
- 模板参数是否可以是引用类型?
- 数组类型在函数调用中用作引用类型参数
- C++为什么atomic_load参数的类型是指针而不是引用?
- 当 std::initializer_list 用作赋值参数时,为什么它不是引用类型?
- 使用了引用类型和odr的模板非类型参数
- 作为非类型模板参数引用
- 使用引用类型作为参数从 C# 调用 C++ 函数
- 为什么当 T 是引用类型时,const T& 参数中的 const 会消失?
- C++:将引用类型显式指定为类型参数的模板函数
- 获取模板参数指定类型的对象的虚拟引用