The static_cast operator (C++ only)
The static_cast operator converts a given expression to a specified type.
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).
- If Type is an lvalue reference type or an rvalue reference to a function type, static_cast<Type>(expression) is an lvalue.
- If Type is 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.25
In 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 A to type B&, and the cast result is an lvalue of type B
- An lvalue or xvalue of type A to type B&&, and the cast result is an xvalue of type B
- A (prvalue) rvalue of pointer to A to pointer to B
- An lvalue of type A to type B&& if an xvalue of type A can be bound directly to a reference of type B&&
- An expression e to type T if the direct initialization T t(e) is valid.
- A is a base class of B.
- There exists a standard conversion from a pointer to type B to a pointer to type A.
- Type B is the same as or more cv-qualified than type A.
- A is not a virtual base class or a base class of a virtual base class of B.
- B is a base class of A.
- There exists a standard conversion from a pointer to member of B whose type is T to a pointer to member of A whose type is T.
- cv2 is the same or more cv-qualification than cv1.
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.