bit-field in overload resolution for template

前端 未结 1 1650
甜味超标
甜味超标 2021-01-14 14:19

Anyone knows why the first program compiles but second one doesn\'t? The only difference is that the first one uses normal function but the second one uses template functio

1条回答
  •  孤街浪徒
    2021-01-14 14:38

    The error is quite clear, you cannot take non-const references to bitfields. [class.bit]/3:

    The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields. A non-const reference shall not be bound to a bit-field (8.5.3). [ Note: If the initializer for a reference of type const T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly. See 8.5.3. —end note ]

    The reason overload resolution behaves differently has to do with Universal References. Reference collapsing rules and templates make this:

    template 
    void f(T&& x) {}
    

    result in T&& to be deduced as int& when applied to a non-const lvalue int, which is the case for x.x. In that particular case, you are left with:

    void f(int& x){}
    void f(int const& x){}
    

    and the first one, the one obtained from reference collapsing rules on f(T&& x), it can be clearly seen to be a better match than the later one.

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