2012-11-21 4 views
0

내가 가진 가정 내 테스트에서기본 클래스에 대한 참조를 boost :: thread에 전달하고 파생 클래스에서 가상 함수를 호출 할 수 있습니까?

class Base 
{ 
    public: 

     void operator()() 
     { 
      this->run(); 
     } 

     virtual void run() {} 
} 

class Derived : public Base 
{ 
    public: 

     virtual void run() 
     { 
      // Will this be called when the boost::thread runs? 
     } 
} 

int main() 
{ 
    Base * b = new Derived(); 
    boost::thread t(*b); // <-- which "run()" function will be called - Base or Derived? 
    t.join(); 
    delete b; 
} 

, 나는 Derived::run() 호출 할 수 없습니다. 나는 잘못된 것을하고 있습니까, 아니면 불가능합니까?

답변

0

@ GManNickG의 의견은 가장 명확한 답변이며 완벽하게 작동합니다. 부스트. 레프가가는 길입니다.

thread t(boost::ref(*b)); 
2

*b을 전달하면 Derived 개체 (실제로 값을 기준으로 Base)를 전달합니다. 이 같은 포인터 (또는 스마트 포인터)로 Derived 펑을 통과해야 : 물론

thread t(&Derived::operator(), b); // boost::bind is used here implicitly 

b 수명에주의를 기울이십시오.

+2

또는'boost :: ref (* b)'를 전달하십시오. – GManNickG