The static_cast operator (C++ only)
The static_cast operator converts a given expression to a specified type.
static_cast operator syntax
With the right angle bracket feature,
you may specify a template_id as Type in
the static_cast operator with the >> token
in place of two consecutive > tokens. For details,
see Class templates (C++ only).
static_cast<Type>(expression) belongs to one
of the following value categories:- If
Typeis an lvalue reference type
or an rvalue reference
to a function type
, static_cast<Type>(expression)is an lvalue.
If Typeis an rvalue reference to an object type,static_cast<Type>(expression)is an xvalue.
- In all other cases,
static_cast<Type>(expression)is a
(prvalue)
rvalue.
An example of the static_cast operator:
#include <iostream>
using namespace std;
int main() {
int j = 41;
int v = 4;
float m = j/v;
float d = static_cast<float>(j)/v;
cout << "m = " << m << endl;
cout << "d = " << d << endl;
}m = 10
d = 10.25In this example, m = j/v; produces an
answer of type int because both j and v are
integers. Conversely, d = static_cast<float>(j)/v; produces
an answer of type float. The static_cast operator
converts variable j to type float.
This allows the compiler to generate a division with an answer of
type float. All static_cast operators
resolve at compile time and do not remove any const or volatile modifiers.
Applying the static_cast operator to
a null pointer converts it to a null pointer value of the target type.
- An lvalue of type
Ato typeB&, and the cast result is an lvalue of typeB
An lvalue
or xvalue of type Ato typeB&&, and the cast result is an xvalue of typeB
- A
(prvalue)
rvalue of pointer to Ato pointer toB
An lvalue
of type Ato typeB&&if an xvalue of typeAcan be bound directly to a reference of typeB&&
- An expression
eto typeTif the direct initializationT t(e)is valid.
Ais a base class ofB.- There exists a standard conversion from a pointer to type
Bto a pointer to typeA. - Type
Bis the same as or more cv-qualified than typeA. Ais not a virtual base class or a base class of a virtual base class ofB.
(prvalue)
rvalue of a pointer to member of A whose
type is cv1 T to a
(prvalue)
rvalue of a pointer to member of B whose
type is cv2 T if the following conditions are satisfied:Bis a base class ofA.- There exists a standard conversion from a pointer to member of
Bwhose type isTto a pointer to member ofAwhose type isT. cv2is the same or more cv-qualification thancv1.
You can explicitly convert a pointer to cv1
void to a pointer to cv2 void if cv2 is
the same or more cv-qualification than cv1.