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