The C++ casts static_cast
, const_cast
, reinterpret_cast
have a template-like syntax, e.g.
long foo = 3;
int bar = static_cast<int>(foo);
I've looked in the Standard, and it says that casts are expressions, not template functions as I thought.
This left me wondering: under the hood, are these casts just templates with privileged status, or are they keywords that happen to borrow the template syntax?
are they keywords that happen to borrow the template syntax?
This. Casts are implemented differently depending on the context they are used in – in general, they cannot be implemented as functions. For instance, static_cast
is sometimes only a compile-time operation, no code is emitted for it. But other times (in particular when invoking constructors, casting in a type hierarchy or converting between layout-incompatible primitive types) it requires a runtime operation.
That said, you can implement your own functions that resemble the standard cast syntax (boost::lexical_cast
does that).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With