by sesuximo · 5y ago · 0 comments
https://shafik.github.io/c++/undefined%20behavior/2019/05/11...
C++ namespaces are a way to avoid library A's symbol "cow" clashing with library B's symbol "cow" without everything being named library_a_cow and library_b_cow all over the place which is annoying. I agree C would be nicer with such a namespace feature.
However this technique is about what happens when you realise your structure members x and y should be inside a sub-structure position, and you want both:
d = calculate_distance(s.x, s.y); // Old code
and
d = calculate_distance(s.position.x, s.position.y); // New
... to work while you transition to this naming.
Secondly this technique does something different. The C hack doesn't touch the old code. But this "inline namespace" trick means old code has to explicitly opt into this backward compatibility fix or else it might blow up.
Lastly, I didn't try this, but presumably you did. Are the two separately namespaces classes the "same thing" as far as type checking is concerned? A vital feature of this union trick is that it's just one structure, it type checks as the same structure because it is the same structure. At a glance, I think the C++ solution results in two types with similar names, so that would fail type checking.
I suppose migration is another possible use case for the union trick, and for that case C++ inline namespaces can be used as part of an implementation that achieves a broadly similar goal, but in a completely different way. As tialaramex notes, with inline namespaces you still end up with two different types.