在传递可变参数时保留引用性
Preserving referenceness when passing variadic arguments
请考虑以下代码片段:
class Base
{
public:
template <typename...Ts>
void fun(Ts... vs)
{
cout << "Base::fun" << endl;
cout << __FUNCSIG__ << endl;
}
};
template <typename...Ts>
class Derived : public Base
{
public:
void dfun(Ts... vs)
{
cout << "Derived::dfun" << endl;
cout << __FUNCSIG__ << endl;
fun(vs...);
}
};
int main()
{
int i = 10;
int & a = i;
Derived<int, int &> d;
d.dfun(i, a);
}
在VS2013中运行上述代码时,我得到了在Derived::d fun是(int,int&)中为参数包值推断的类型,而在Base::fun是(int,int)中。为什么传递参数时会丢失参考性?
如果dfun和fun是自由函数,则保留了参考性。为什么会有这种差异?
如果我将 Base::fun的签名更改为 Base::fun(Ts&&...vs),再次保留参考性。
在模板推导期间,引用类型将推导到它们所引用的类型。所以int&
将被推导出为int
.这就是导致你所看到的行为的原因。
有关更详细的说明,请参阅此处。
相关文章:
- 将对象数组的引用传递给函数
- 保留对其他类的成员函数的引用
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 如果引用应该保留,不删除析构函数中的指针会导致内存泄漏吗?
- 引用保留向量中的第一个元素
- 此常量引用是否保留了其生命?
- 有没有办法在对象上保留弱引用并控制其生存期
- 如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
- 是否在值类型列表中保留引用类型
- 引用保留名称肯定是违法的吗
- 在传递可变参数时保留引用性
- C++:为智能指针的字段隐式保留右值引用
- 保留对象和对在函数中创建的对象的引用
- 通过引用函数传递向量,但更改不会保留
- JNI保留对对象的全局引用,并使用其他JNI方法访问它.在多个JNI调用中保持C++对象的活动状态
- 如何在 c++ 中保留类之间的多个引用
- c++在不知道其参数的情况下保留对模板实例的引用
- 删除左值,保留左值引用(标准类型特征可用?)
- 如何在c++1y中保留cv限定符或返回类型推导中的引用
- 如何保留引用