Why is operator=(int)
selected here, instead of "ambiguous" or the other one?
{}
to int
is the identity conversion ([over.ics.list]/9). {}
to S
is a user-defined conversion ([over.ics.list]/6) (technically, it's {}
to const S&
, and goes through [over.ics.list]/8 and [over.ics.ref] first before coming back to [over.ics.list]/6).
The first wins.
Is there a tidy workaround?
A variation of the trick std::experimental::optional
pulls to make t = {}
always make t
empty.
The key is to make operator=(int)
a template. If you want to accept int
and only int
, then it becomes
template<class Int, std::enable_if_t<std::is_same<Int, int>{}, int> = 0>
S& operator=(Int t) { a = t; return *this; }
Different constraints can be used if you want to enable conversions (you'd probably also want to take the argument by reference in that case).
The point is that by making the right operand's type a template parameter, you block t = {}
from using this overload - because {}
is a non-deduced context.
...without changing S
?
Does template<class T> T default_constructed_instance_of(const T&) { return {}; }
and then s = default_constructed_instance_of(s);
count?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…