Re: Constructor question...
On Wednesday, 20 February 2013 04:03:17 UTC+2, Luca Risolia wrote:
On 20/02/2013 00:44, =D6=F6 Tiib wrote:
struct A {
A(int = 0) {};
operator int() {};
};
Such class won't pass majority of reviews. Anything that is converting =
to
arithmetic type silently won't pass. It is close to worst error-prone
thing that C++ can deliver.
That's perfectly evident, but it's not relevant to the question. If you=
want, you can easily generalize the example to any type; after all,
despite of any reviews, it's quite common to see "lazy" data types
implemented with *implicit* convertions from one type to another one
*and* viceversa. I personally consider that a design flaw, yes, but,
again, this is another issue.
My point was that if OP uses that obscure and generally frowned upon
idiom (round-trip implicit conversions) then, yes, you are right
that some of the suggestions that we provide do not compile.
However on that case he likely benefits more from suggestion to stop
using that idiom than from a technique how to construct same object
of such a type in different branches.
source.cpp:9:13: error: conditional expression is ambiguous; 'int' can
be converted to 'A' and vice versa
A a(true ? x : y);
The error message would perfectly tell the reason why the whole code
should be deleted ... so that is great then. Code deleted, no problem.
There is no need to delete the whole code. The solution is to modify the=
type by making the convertion in one direction explicit.
Note that in C++11 if you make the operator explicit, "A a (cond ? x :
y)" will compile without modifications.
There you are correct indeed, I was too harsh in my judgement.