Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are C++ casts implemented?

Tags:

c++

casting

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?

like image 934
Ari Avatar asked Jul 17 '12 19:07

Ari


1 Answers

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).

like image 155
Konrad Rudolph Avatar answered Oct 13 '22 08:10

Konrad Rudolph