Timer class 검토 좀 해주세요~

Posted at 2008. 11. 18. 23:20 // in S/W개발/C++ 이야기 // by 김윤수



Timer class 를 아래와 같이 구현하려고 하는데... 괜찮은 설계일까요?

struct Timer
{
    typedef boost::function<void ()> CallbackObjectType;

    Timer(int period, CallbackObjectType cbo) :
        m_period(period), m_cbo(cbo)
    {}

    int m_period;
    CallbackObjectType m_cbo;
};

inline Timer
MakeTimer(int period, void (*func)())
{
    Timer::CallbackObjectType cbo = func;
    return Timer(period, cbo);
}

template <typename Callee>
struct CallbackMemFunc0 {
    typedef void (Callee::*Type)();
};

template <typename Callee>
inline Timer
MakeTimer(int period, Callee* callee, const typename CallbackMemFunc0<Callee>::Type& memFunc)
{
    return Timer(period, boost::bind(memFunc, callee));
}

template <typename ArgType>
struct CallbackFunc1 {
    typedef void (*Type)(ArgType);
};

template <typename ArgType>
inline Timer
MakeTimer(int period, const typename CallbackFunc1<ArgType>::Type& func, ArgType arg)
{
    return Timer(period, boost::bind(func, arg));
}

template <typename Callee, typename ArgType>
struct CallbackMemFunc1 {
    typedef void (Callee::*Type)(ArgType);
};

template <typename Callee, typename ArgType>
inline Timer
MakeTimer(int period, Callee* callee,
          const typename CallbackMemFunc1<Callee, ArgType>::Type& memFunc,
          ArgType arg)
{
    return Timer(period, boost::bind(memFunc, callee, arg));
}

굳이 Timer class는 encapsulation 시킬 필요가 없다고 생각해서 그냥 struct로 선언해 버렸구요. MakeTimer를 여러개 만들어 놓았는데... 아무리 봐도 맘에 안드네요. 결국은 계속해서 반복되는 코드 패턴이라서... 게다가 컴파일러가 template <typename Callee> MakeTimer(...) 와  template <typename ArgType> MakeTimer(...)를 잘 구분못해서 사용자가 직접 template 인자를 알려줘야 해서 불편하기도 하고...

    // Timer t(100, bind(&Base::print, new Base()));
    Timer t1 = MakeTimer(100, new Base(), &Base::print);
    t1.m_cbo();

    Timer t2 = MakeTimer<const string>(100, sayHelloTo, string("YoonSoo Kim"));
    t2.m_cbo();
   
    Timer t3 = MakeTimer(100, new Hello(), &Hello::sayHelloTo, string("YoonSoo Kim"));
    t3.m_cbo();

이렇게 반복되는 코드 없이 깔끔하게 설계할 수 있는 방법은 없을까요????