2016-10-18 6 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

나는 c1을 함수로 만들고 싶습니다. reinterpret_cast는 int를 double로 변환 할 수 없습니다. – lnvm

+0

@ Gr.Five, 업데이트 된 답변을 참조하십시오. –

+0

@R Sahu, 멋지다! 그것은 효과가 있지만 왜 설명해 주시겠습니까? – lnvm