2016-10-18 24 views
0

コード:非静的メンバ関数reinterpret_castは失敗しました

#include <iostream> 

using namespace std; 

struct item 
{ 
    int f1() {} 
    double f2() {} 

    static int g1() {} 
    static double g2() {} 

    void f0(); 
}; 
void item::f0() 
{ 
    auto c1 = reinterpret_cast<decltype(f2)>(f1); 
    auto c2 = reinterpret_cast<decltype(g2)>(g1); 

    auto c3 = reinterpret_cast<decltype(&f2)>(f1); 
    auto c4 = reinterpret_cast<decltype(&g2)>(g1); 
} 
int main() 
{ 
    cout << "Hello world!" << endl; 
    return 0; 
} 

エラーメッセージ:

main.cpp|17|error: invalid use of non-static member function| 
main.cpp|18|error: invalid cast from type ‘int (*)()’ to type ‘double()’| 
main.cpp|20|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&item::f2’ [-fpermissive]| 
main.cpp|20|error: invalid use of member function (did you forget the ‘()’ ?) 

私の質問:引数として渡された メンバ関数が自動的にポインタに変換されますので、私はキャストしてみてくださいポインターへの引き数ですが、引き続き失敗しました。 非スタティックメンバー関数がすべて 状況で機能しない理由を理解できません。

答えて

0

f1の戻り値をキャストする必要があります( f1ではなく)。使用:

auto c1 = reinterpret_cast<decltype(f2())>(f1()); 
               ^^ Call the function 

他の行と同様の変更を加えます。

私はあなたがしたことを誤解しました。以下の作業をする必要があります:

auto c1 = reinterpret_cast<decltype(&item::f2)>(&item::f1); 
    auto c2 = reinterpret_cast<decltype(&g2)>(g1); 

    auto c3 = reinterpret_cast<decltype(&item::f2)>(&item::f1); 
    auto c4 = reinterpret_cast<decltype(&g1)>(g2); 

f1を非staticメンバ関数です。 f1()を使用して呼び出すことができます。ただし、関数呼び出しの構文がないと、非静的メンバー関数はメンバー関数ポインタに自動的には減衰しません。 structのメンバー関数ポインタを取得するには、&item::f1を使用する必要があります。

+0

私は関数をreinterpret_castに加えて、intをdoubleに変換することはできません。 – lnvm

+0

@ Gr.Five、更新された答えをご覧ください。 –

+0

@R Sahu、素晴らしい!それは動作しますが、理由を説明できますか? – lnvm

関連する問題