C++ comes with four built-in casts.
static_cast
dynamic_cast
const_cast
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?
In-built type casting functions in C:-atof(): Used for converting the string data type into float data type. atoi(): Used for converting the string data type into int data type. atbol(): Used for converting the string data type into long data type. itoba(): Used for converting the int data type into string data type.
Typecasting is a method in C language of converting one data type to another. There are two types of typecasting. 1. Implicit Type casting − This conversion is done by the compiler.
The cast operator is a unary type operator that temporarily transforms an expression, variable, or constant to a specific data type. Syntax: (data-type)expression; Here the data type is the type in which we are converting the expression, where the expression could be either a variable, constant, or an expression.
Understanding Type Casting in Java Programmers need to check the compatibility of the data type they are assigning to another data type, in advance. Typecasting is automatically performed if compatibility between the two data types exists. This type of conversion is called automatic type conversion.
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; }
There's also the function-style cast which looks like a function or constructor call. This resolves to the constructor call for classes, and (more generally) to C-style casts for all other types.
Examples:
int x = int(1.0); // equals `(int)1.0`
string s = string("x"); // equals call to constructor
The call to a constructor can also be achived using an explicit cast (apart from the C-style cast which would also work):
string s = static_cast<string>("x"); // is the same as above!
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