코드 중복을 피하기 위해 함수에 대한 포인터를 정적 메서드의 인수로 전달하려고합니다.포인터를 메서드로 인수로 사용
정적 메서드 만 사용하는 클래스 (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;
}
고마워요. 나는'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
@ n3squik, 오, 죄송합니다. 나는 그 때 나의 대답을 업데이트 할 것이다. – chris