在传递可变参数时保留引用性

Preserving referenceness when passing variadic arguments

本文关键字:保留 引用 参数 变参      更新时间:2023-10-16

请考虑以下代码片段:

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.这就是导致你所看到的行为的原因。

有关更详细的说明,请参阅此处。