2014-12-05 2 views
0

나는 엔진을 만들고있다. 별도의 클래스에서 포인터로 함수를 호출하는 Timer 클래스를 생성해야합니다. 예를 들어 :포인터를 사용하여 클래스에서 함수를 호출하는 방법은 무엇입니까?

요약에서
class MyTimer { 
public: 
    void setTimeoutFunction(_pointer_, unsigned short timeoutMs) { 
     // here we need to have a opportunity to store a _pointer_ to a function 
    } 
    void tickTimer() { 
     ... 
     // here I need to call a function by a pointer 
     ... 
    } 
}; 

// Main class: 
class MyAnyClass { 
public: 
    void start() { 
     MyTimer myTimer; 
     myTimer.setTimeoutFunction(startThisFunc, 1500); // 1500ms = 1.5s 
     while (true) { 
      myTimer.tickTimer(); 
     } 
    } 
    void startThisFunc() { ... } 
} 

, 어떻게 당신은 어떤 클래스에 속하는 함수에 대한 포인터를 저장 않으며 포인터에 의해 그 함수를 호출?

+0

이 질문에 좋은 답변을 얻을 너무 광범위하지만 어쩌면 원하는 것을 보관할 수있는 [std :: function] (http://en.cppreference.com/w/cpp/utility/functional/function)을 살펴보아야합니다. – mkaes

+0

한 번에 하나의 개체에 대해 하나의 전용 타이머가 항상 있어야합니까? 아니면 단일 타이머 개체가 다른 형식의 여러 개체를 처리 할 수 ​​있어야합니까? –

+0

@KerrekSB 한 번에 한 개체에 하나의 타이머가 필요합니다. – JavaRunner

답변

1

, 내가 타이머를 클래스 템플릿을 추천 할 수 있습니다

template <typename T> 
struct MyTimer 
{ 
    using FuncPtr = void (T::*)(); 

    MyTimer(FuncPtr ptr, T * obj, unsigned int timeout_ms) 
    : ptr_(ptr), obj_(obj), timeout_ms_(timeout_ms) {} 

    void tickTimer() 
    { 
     (obj_->*ptr_)(); 
    } 

    FuncPtr ptr_; 
    T * obj_; 
    unsigned int timeout_ms_; 
}; 

사용법 :

struct MyAnyClass 
{ 
    void start() 
    { 
     MyTimer<MyAnyClass> myTimer(&MyAnyClass::startThisFunc, this, 1500); 
     while (true) { myTimer.tickTimer(); } 
    } 

    void startThisFunc() { /* ... */ } 
}; 
+0

와우, 멋진 트릭입니다. 감사! 어떻게 든 "사용"키워드없이이 샘플을 사용할 수 있습니까? C++ 11 스타일이지만 불행하게도 현재 C++ 11을 사용할 수 없다고 생각합니다. – JavaRunner

+0

여기에 : http://en.cppreference.com/w/cpp/language/type_alias 나는 샘플을 발견했다 :'func = void (*) (int, int); 사용 -'typedef void와 동일한 타입 별명 (* func) (int, int); ' 내가 필요한 것 같아. :) – JavaRunner

0

C++ 11에서는 std :: function을 사용할 수 있습니다. 사용법에 대한 좋은 가이드는 다음과 같습니다. http://en.cppreference.com/w/cpp/utility/functional/function

원하는 대소 문자 만 포함하는 새로운 코드 스 니펫을 만들었습니다. 당신의 요구 사항은

#include <stdio.h> 
#include <functional> 
#include <iostream> 

struct Foo { 
    Foo(int num) : num_(num) {} 
    void print_add(int i) const { std::cout << num_+i << '\n'; } 
    int num_; 
}; 


int main() 
{ 
    // store a call to a member function 
    std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; 
    const Foo foo(314159); 
    f_add_display(foo, 1); 

    return 0; 
} 
관련 문제