首页 > 解决方案 > 右值和左值引用上的函数模板重载

问题描述

在关于“参考折叠”“在 r-values 和 l-values 上重载函数模板”的 c++ 入门中说:

template <typename T> void f(T&&); // binds to nonconst rvalues
template <typename T> void f(const T&); // lvalues and const rvalues

“与非模板函数一样,第一个版本将绑定到可修改的右值,第二个版本将绑定到左值或 const 右值。”

这个例子来自书中,但我认为有点不同:

第一个版本将绑定到可修改的右值和可修改的左值:

template <typename T>
void foo(T&& x)
{
    cout << "foo(T &&)\n";
}

template <typename T>
void foo(T const& x)
{
    cout << "foo(T const&)\n";
}


int main()
{

    int i = 21;
    int const ic = i;
    foo(5); // foo(int&&)
    foo(i); // foo(int&& ) -> new instantiation foo(int& x) --- here
    foo(ic); // foo(int const&)
    foo(std::move(i)); // foo(int&&)
    foo(std::move(ic));// foo(&&) -> foo(int const&&)


    cout << "\ndone!\n";
}

正如你所看到的,当我传递i一个可修改的左值时,它foo(int&&)被称为不是foo(int const&)编译器将应用引用折叠产生以这种方式实例化一个版本的 foo :

 void foo(int& x){}; // after reference collapsing

因此,仅当参数是常量 l 值或 const r 值时,才首选引用 const l 值的版本。(重载解析和功能匹配)

这就是我的想法。你怎么看?谢谢!

标签: c++templatesoverloadingrvalue-referencetype-deduction

解决方案


推荐阅读