一、Cスタイルの型変換
1.1 暗黙的な型変換
暗黙的な型変換(Implicit Type Conversion)は、コンパイラがコンパイル段階で自動的に行う変換です。代表的な例:
- 代入演算子での変換: intからdoubleへの変換
- 算術演算子での変換: intとlongの演算でlongに昇格
- 関数呼び出しでの変換: 実引数と仮引数の型不一致時の変換
- 真偽値変換: 非ゼロ値→true、ゼロ値→false
- ポインタ変換: void*への暗黙変換、配列名→先頭要素ポインタ
void process(double value) {}
void example()
{
int num = 10;
double decimal = num; // 代入変換
double result = num + decimal; // 算術変換
process(num); // 関数引数変換
void* ptr = # // ポインタ変換
}
1.2 明示的な型変換
明示的な型変換(Explicit Type Conversion)は、プログラマが直接指定する強制変換です。
void example()
{
int num = 10;
double decimal = (double)num; // キャスト演算子
}
二、C++スタイルの型変換
2.1 static_cast
非多態型で類似した型間の変換に使用:
void example()
{
int num = 10;
double decimal = static_cast<double>(num);
int* int_ptr = #
void* void_ptr = static_cast<void*>(int_ptr);
}
2.2 dynamic_cast
多態型のダウンキャストに使用(実行時チェック):
class Parent {
public:
virtual void method() {}
int parent_data = 1;
};
class Child : public Parent {
public:
virtual void method() {}
int child_data = 2;
};
void process(Parent* base_ptr)
{
Child* derived_ptr = dynamic_cast<Child*>(base_ptr);
if(derived_ptr) {
derived_ptr->parent_data++;
derived_ptr->child_data++;
} else {
cout << "変換失敗" << endl;
}
}
2.3 const_cast
const/volatile属性の追加・削除:
void example()
{
volatile const int value = 5;
int* mutable_ptr = const_cast<int*>(&value);
*mutable_ptr = 10;
cout << value << endl;
cout << *mutable_ptr << endl;
printf("%p\n", &value);
cout << mutable_ptr << endl;
}
2.4 reinterpret_cast
非類似型間の低レベル再解釈:
void example()
{
int num = 10;
int* int_ptr = #
double* double_ptr = reinterpret_cast<double*>(int_ptr);
}
三、RTTI(実行時型情報)
3.1 typeid演算子
void example()
{
auto lambda = [](int a, int b){ return a + b; };
cout << typeid(lambda).name() << endl;
}
3.2 decltype
void example()
{
int x = 5;
double y = 3.14;
auto result = x * y;
vector<decltype(result)> container;
}
C++型変換は可視性と安全性を向上させます:
- static_cast: 類似型変換
- dynamic_cast: 多態型ダウンキャスト
- const_cast: const属性操作
- reinterpret_cast: 非類似型変換