C++ – What other useful casts can be used in C++


C++ comes with four built-in casts.

  1. static_cast
  2. dynamic_cast
  3. const_cast
  4. reinterpret_cast

Not to meantion the frowned upon C (style*)cast.

Additionally boost supplies a lexical_cast, are there any other useful casts that you use or would like to exist?

Best Solution

My favorite and most loved cast is implicit_cast. It only succeeds if the types can be implicitly converted.

Useful for conversion from some type into void* or from some derived class into a base (if you want to select a specific instance of an overloaded function or constructor) or to safely add const-qualifications and any other scenario where you really just need implicit conversions to happen and even static_cast is too powerful.

Also read How does C++ pick which overload to call.

boost/implicit_cast.hpp. You can add this to your code collection too, if you want

template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }