2013-05-30 5 views
0

코드 중복을 피하기 위해 함수에 대한 포인터를 정적 메서드의 인수로 전달하려고합니다.포인터를 메서드로 인수로 사용

정적 메서드 만 사용하는 클래스 (Geo)가 있습니다. 이 방법 중 하나 (+++ Geo :: traceRay (+++))는 단지 몇 가지를 표시하고 (Geo :: display (+++)) int를 반환해야합니다.

다른 클래스 (Las)는 Geo :: traceRay (+++) 메소드를 사용해야하지만 다른 클래스는 (Las :: display (+++)) 표시해야합니다. 그래서 함수 인수에 대한 포인터를 Geo :: traceRay (+++, 함수 포인터) 메서드에 전달하려고합니다. pointed functon은 올바른 "display()"메소드가 될 것입니다.

지금까지 display()에 첫 번째 포인터를 전달하는 것은 문제가 아니지만 두 번째 포인터로 처리하는 방법을 찾을 수 없습니다.

class Geo 
{ 
public: 
    static bool display(int pix); 
    static int traceRay(int start, int end, bool (*func)(int) = &Geo::display); // no issue with this default parameter 
}; 


class Las 
{ 
public: 
    bool display(int pix); 
    void run(); 
}; 


int Geo::traceRay(int start, int end, bool (*func)(int)) 
{ 
    for (int i = start; i < end ; ++i) 
    { 
     if((*func)(i)) return i; 
    } 
    return end; 
} 

bool Geo::display(int pix) 
{ 
    cout << pix*100 << endl; 
    return false; 
} 


bool Las::display(int pix) 
{ 
    cout << pix << endl; 
    if (pix == 6) return true; 
    return false; 
} 

void Las::run() 
{ 
    bool (Las::*myPointerToFunc)(int) = &display;  // I can just use display as a non member class, but it should stay a member 
    Geo::traceRay(0,10, myPointerToFunc);    // issue here! 
} 


int main() 
{ 
    Geo::traceRay(0,10); // use the "normal display" = the default one// OK 

    Las myLas; 
    myLas.run(); 

    return 0; 
} 

답변

0

멤버 함수 포인터를 함수 포인터로 전달할 수 없습니다. 나는 Las::display 정적을 만드는 것이 옵션이 아니라고 추정합니다. 그것은 역 참조 할 필요

func(i); 

:

static int traceRay(int start, int end, std::function<bool(int)> func = &Geo::display); 
... 
Geo::traceRay(0,10, std::bind(&Las::display, this, std::placeholders::_1)); 

또한, 두 경우 모두, 당신은에 의해 func를 호출 할 수 있습니다 :이 경우에 나는 std::function 복용하고 현재 인스턴스를 바인딩 std::bind을 사용하는 것이 좋습니다 것입니다 먼저.

+0

고마워요. 나는'std :: function'과'std :: bind'를 몰랐다. 나는 그것이 어떻게 작동하는지 이해하기 위해 [link] (http://latedev.wordpress.com/2012/08/06/using-stdbind-for-fun-and-profit/)가 필요했지만, 지금 나는 내가 원했던 바를 정확히 가지고있다. 또한 Las 클래스에서 Geo :: traceRay를 호출하기 위해서는'Geo :: traceRay (0,10, std :: bind (& Las :: display, this, std :: placeholders :: _ 1));' – n3squik

+0

@ n3squik, 오, 죄송합니다. 나는 그 때 나의 대답을 업데이트 할 것이다. – chris

0

크리스가 제안한 내용은 그것이 가능한 한 훌륭합니다.

이와 같은 몇 가지 공유 기능이있는 경우 유리한 또 다른 접근 방법은 두 개의 구현이있는 인터페이스 (가상 메소드 Display (+++))를 사용하고 구현의 인스턴스를 넣는 것입니다 Geo와 Las (또는 Las는 인터페이스를 직접 구현할 수 있습니다.) 각각의 질문에서. 그런 다음 traceRay는 인터페이스 기본 클래스에 대한 참조를 가져 와서 표시 메소드를 호출합니다.

관련 문제