Visual C++ 2010, rvalue reference bug?

前端 未结 2 1315
自闭症患者
自闭症患者 2021-01-06 05:42

Is it a bug in Visual C++ 2010 or right behaviour?

template
T f(T const &r)
{
    return r;
}

template
T f(T &&r)
         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-06 06:27

    As I understand it (and I may not be completely right; the specification is a bit complicated), the template type deduction rules conspire against you.

    The compiler first attempts to substitute all templates (it's not choosing at this point yet—just looking for options) and gets:

    • T const &r matches int lvalue with T = int, creating f(int const &)
    • T &&r matches int lvalue with T = int& and int & && reduces to int&, creating f(int &) (there are rules saying this in the spec).

    Now it comes to selecting correct overload and the later is better match, because the first differs in cv-qualification and the later does not. That's also the reason why when you remove the const, you get ambiguous overload error—the overloads end up being exactly the same.

    Ad Update1: gcc supports many of the C++0x features. You can get native windows build from mingw or use cygwin.

    Ad Update2: If you really need separate overloads for rvalue and lvalue, that seems to be the only option. But most templates do the right thing with just any kind of reference, perhaps using std::forward to ensure proper resolution of functions they call depending on whether they got rvalue or lvalue).

提交回复
热议问题