Assume we have procedure void f(X2);
. Further assume we have types X1
and X2
that do not share an inheritance hierarchy.
We want to call it like this: f(X1{})
and have X1
implicitly convert into X2
. We have two options of achieving this:
struct X2 {};
struct X1 { operator X2(); };
struct X1 {};
struct X2 { X2(const X1&); };
Implementation-wise there are practical differences between the two with the order things are defined and how private data is accessed.
But from a user perspective, are there any cases where these two approaches will behave differently? If so, which of the two is preferable?
This question remains the same even if we mark both explicit
. One difference that arises then is that conversion through the constructor is only available in the former case but static_cast
works with either.
std::string
but the other way around is fine and part of the standard library. The use case I am facing is very similar to this – PantojaX2
with that data – Pantoja