explicit_cast
So we have
duration_cast<To>(from)
quantity_cast<To>(from)
quantity_point_cast<To>(from) https://github.com/mpusz/units/pull/118
All these functions perform an explicit cast between different types in their type family when an implicit cast is not allowed. Now what sounds familiar about that? That is right , generic programming
Would it not be more elegant to express this with a common name for this function parameterised by type such as
explicit_cast<To>(From)
There are actually much more of those in the standard library: pointer_cast, any_cast, clock_cast, time_point_cast. In general, I like your suggestion but even if we do it for the units library it will cover only a small part of the domain here. Maybe it is a good idea to write a separate ISO proposal against all of those in order to unify things?
There are actually much more of those in the standard library:
pointer_cast,any_cast,clock_cast,time_point_cast. In general, I like your suggestion but even if we do it for the units library it will cover only a small part of the domain here. Maybe it is a good idea to write a separate ISO proposal against all of those in order to unify things?
Having looked at pointer_xx_cast and any_cast I think, if it was done , it was best to avoid the pointers and any and limit the initial scope ( simply because of time and complexity). so its function would be to cast between objects representing dimensionally equivalent quantities,but with different internals, which require user to runtime validate e.g double -> int rep_type, cast to different units with risk of overflow etc
To that end one use might be to cast between the two types of time:
std::chrono::seconds t{1};
Quantity q = explicit_cast<si::time<si::second> >(t);
I think there is a point to this proposal, but IMHO it needs to be approached with care. After all, even if we just look at the standard static_cast, reinterpret_cast etc., they all perform an explicit cast where an implicit cast is not allowed. The C++ community long agreed that this is much better than the C-style cast which can do all at once.
The reason why we have different names for them, is because we want to explicitly limit them to a specific semantic operation. In the case of the three casts mentioned in this issue, they all enable casting between different representations of the same concept but are not implicit because they may loose information in the process. So I would suggest a name like imprecise_representation_cast or similar. That makes it semantically clear what it is about and separates it from other casts like e.g. const_cast which do change the concept, not the representation.
Addressed in V2