次のコードは、GCCの上にきれいにコンパイルしますが、クラン上のエラーを取得します。constを関数ポインタにキャストする方法はありますか?
typedef void (MyFuncPtr)();
void foo(const MyFuncPtr* ptr)
{
MyFuncPtr* myTestPtr = ptr;
}
クランエラー:
error: cannot initialize a variable of type 'MyFuncPtr *' (aka 'void (*)()') with an lvalue of type 'const MyFuncPtr *'
(aka 'void (const *)()')
私は次の解決方法を試してみましたし、彼らはすべてのC-スタイル以外のエラーが出ますキャスト:
はconst_cast:
MyFuncPtr* myTestPtr = const_cast<MyFuncPtr*>(ptr);
エラー:
error: const_cast to 'MyFuncPtr *' (aka 'void (*)()'), which is not a reference, pointer-to-object, or pointer-to-data-member
reintepret_cast:
MyFuncPtr* myTestPtr = reinterpret_cast<MyFuncPtr*>(ptr);
エラー:
error: reinterpret_cast from 'const MyFuncPtr *' (aka 'void (const *)()') to 'MyFuncPtr *' (aka 'void (*)()') casts away
qualifiers
Cスタイルのキャスト:
MyFuncPtr* myTestPtr = (MyFuncPtr*) ptr;
成功!
質問:
const_castが関数ポインタで機能しないのはなぜですか?
Cスタイルのキャストのみを使用していますか?
これはGCCでキャストなしで動作するのはなぜですか?
ありがとうございます!
コンパイラのバージョン:あなたのコードで
* G ++バージョン4.6.3
*打ち鳴らすバージョン3.5.0.210790
'const MyFuncPtr *'型はほとんどナンセンスで無駄です(ほぼ完全に役に立たない)。そして、私が考えることができるすべての使用には*インスタンス*が関連付けられていません。なぜあなたはあなたのプログラムにこのタイプを持っていますか?非常に汎用的なコードですか? – Yakk
'MyFuncPtr'は実際には関数型ではなく、関数ポインタ型ではないことに注意してください(これはあなたの質問を無効にしませんが、実際はもっと面白くなります) –