Overload resolution between object, rvalue reference, const reference

后端 未结 1 1575
抹茶落季
抹茶落季 2020-11-29 00:26

Given all three functions, this call is ambiguous.

int f( int );
int f( int && );
int f( int const & );

int q = f( 3 );

Removi

相关标签:
1条回答
  • 2020-11-29 01:21

    What are the rules here?

    As there is only one parameter, the rule is that one of the three viable parameter initializations of that parameter must be a better match than both the other two. When two initializations are compared, either one is better than the other, or neither is better (they are indistinguishable).

    Without special rules about direct reference binding, all three initializations mentioned would be indistinguishable (in all three comparisons).

    The special rules about direct reference binding make int&& better than const int&, but neither is better or worse than int. Therefore there is no best match:

    S1    S2
    int   int&&         indistinguishable
    int   const int&    indistinguishable
    int&& const int&    S1 better
    

    int&& is better than const int& because of 13.3.3.2:

    S1 and S2 are reference bindings (8.5.3) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference.

    But this rule does not apply when one of the initializations is not a reference binding.

    Is there any chance int && may be preferred over int in a future standard? The reference must bind to an initializer, whereas the object type is not so constrained. So overloading between T and T && could effectively mean "use the existing object if I've been given ownership, otherwise make a copy."

    You propose to make a reference binding a better match than a non-reference binding. Why not post your idea to isocpp future proposals. SO is not the best for subjective discussion / opinion.

    0 讨论(0)
提交回复
热议问题