型の変換 解答ページ | Programming Place Plus Modern C++編【言語解説】 第9章

トップページModern C++編 C++編](../../index.html) – 第9章

Modern C++編は作りかけで、更新が停止しています。代わりに、C++14 をベースにして、その他の方針についても見直しを行った、新C++編を作成しています。
Modern C++編は削除される予定です。

問題①

問題① 次の各変換は、static_cast、const_cast、reinterpret_cast、C言語形式のキャスト、キャストは不要、のいずれで行えるか答えてください。

  1. long → short
  2. bool → int
  3. int* → int
  4. const char* → char*
  5. struct MyData* → void*
  6. struct MyData* → const struct MyData*
  7. void* → struct MyData*
  8. const float* → int*
  9. bool (*f)(int) → bool (*f)(const char*)


1. long → short

暗黙的に変換できますが、大きさが小さくなると元の値が表現できない可能性があるため、ほとんどのコンパイラでは警告が出ます。 static_cast か、C言語形式のキャストで、問題がないことを明示できます。 C++ では static_cast を使いましょう。

2. bool → int

キャストは不要です。 true なら 1 に、false なら 0 になります。

3. int* → int

reinterpret_cast か、C言語形式のキャストが使えます。 C++ では reinterpret_cast を使いましょう。

4. const char* → char*

const_cast か、C言語形式のキャストが使えます。 C++ では const_cast を使いましょう。

5. struct MyData* → void*

あるポインタ型から void*型へは、暗黙的に変換できますから、キャストは不要です。

6. struct MyData* → const struct MyData*

const修飾子を付ける方向へは、暗黙的に変換できますから、キャストは不要です。

7. void* → struct MyData*

static_cast、reinterpret_cast、C言語形式のキャストのいずれでも可能です。 C++ では static_cast を使いましょう。

8. const float* → int*

C言語形式のキャストを使えば一気に変換できますが、 C++ では reinterpret_cast と const_cast を併用して書くべきです。

int* p2 = reinterpret_cast<int*>(const_cast<float*>(f));

9. bool (*f)(int) → bool (*f)(const char*)

reinterpret_cast か、C言語形式のキャストが使えます。 C++ では static_cast を使いましょう。

書き方が分かりにくいので、例を挙げておきます。

#include <iostream>

bool func(int a)
{
    return true;
}

int main()
{
    bool (*p1)(int) = func;
//  bool (*p2)(const char*) = (bool (*)(const char*))p1;
    bool (*p2)(const char*) = reinterpret_cast<bool (*)(const char*)>(p1);

    std::cout << p2("abc") << std::endl;
}

実際のところ、関数ポインタの型は分かりづらいので、 using で別名を用意する方が良いでしょう。

#include <iostream>

using func_int = bool (*)(int);
using func_cchar_ptr = bool (*)(const char*);

bool func(int a)
{
    return true;
}

int main()
{
    func_int p1 = func;
//  func_cchar_ptr p2 = (func_cchar_ptr)p1;
    func_cchar_ptr p2 = reinterpret_cast<func_cchar_ptr>(p1);

    std::cout << p2("abc") << std::endl;
}

ただし、キャストができるからといって、安全に使えるかどうかは別問題なので注意してください。 たとえば、このサンプルプログラムにおいては、p2 に代入した関数ポインタは本来、int型が引数の関数を指していますから、 p2(“abc”) のように文字列を渡しても、正常に動作することはないでしょう。



参考リンク


更新履歴

’2017/7/27 新規作成。



第9章のメインページへ

Modern C++編のトップページへ

Programming Place Plus のトップページへ



はてなブックマーク に保存 Pocket に保存 Facebook でシェア
X で ポストフォロー LINE で送る noteで書く
rss1.0 取得ボタン RSS 管理者情報 プライバシーポリシー
先頭へ戻る