Visual C++ 2010, rvalue reference bug?

女生的网名这么多〃 提交于 2019-11-30 22:16:52

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).

Your fix doesn't solve the problem with static_assert firing though. The static_assert(false, ...) will still trigger for compilers that parse templates at definition time (most do).

They will see that any function template instantiation will be ill-formed, and the Standard allows them to issue an error for the template itself then, and most will do so.

For making this work you need to make the expression dependent so that the compiler doesn't know when it parses the template that it will always evaluate to false. For example

template<class> struct false_ { static bool const value = false; };

template<class T>
T f(T &&r)
{
    static_assert(false_<T>::value, "no way"); //< line # 10
    return r;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!