2012-04-21 78 views
1

我有这样的代码:仿函数+成员指针来创建对象的信号

// signal supporter parent 
class signalable {}; 

template <class typeT = signalable> 
typedef void (typeT::*trig)(std::string); 

template <class typeT = signalable> 
class trigger 
{ 
    private: 
     typeT* instance; 
     typeT::trig fun; 

    public: 
     trigger(typeT* inst, typeT::trig function) 
      : instance(inst), fun(function) 
     {} 
     void operator()(std::string param) 
     { 
      (instance->*fun)(param); 
     } 
}; 

我得到许多编译错误的,我敢打赌,专家们都知道的。我只是对这个背景感到困惑。

我想做的事情很清楚:将指针指向一个对象,并指向其中一个成员函数,以制作一个函数并在程序中传递它。

希望你的帮助和“更正”。

谢谢!

+2

本Ç回答了你的问题,但你可能想看看进入[观察者模式(http://en.wikipedia.org/ wiki/Observer_pattern)为我认为是你的**原始**问题的一个很好的方法。 – smocking 2012-04-21 11:42:49

+0

@smocking我很欣赏你的观点,这是我之前处理过的一个案例,但在这种情况下,观察者模式是我的目标,因为在我的代码事件中,要以“链式”方式传播,而不是传播到多个事件被调用者。无论如何,感谢帮助我观察对比。 – Haix64 2012-04-21 12:01:40

+0

我不确定我是否理解为什么你会想要这种信号,但是你不能通过让你的“链式”信号类继承Observer和Observable接口来扩展一些模式吗? – smocking 2012-04-21 12:43:42

回答

0

你想要做这样的事吗?

#include <string> 
#include <iostream> 

// signal supporter parent 
class signalable 
{ 
public: 
    void foo(std::string s) { std::cout << "hello: " << s << std::endl; } 
}; 


template <class typeT = signalable> 
class trigger 
{ 

    typedef void (typeT::*trig)(std::string); 

    private: 
     typeT* instance; 
     trig fun; 

    public: 
     trigger(typeT* inst, trig function) 
      : instance(inst), fun(function) 
     {} 
     void operator()(std::string param) 
     { 
      (instance->*fun)(param); 
     } 
}; 

int main() 
{ 
    signalable s; 
    trigger<> t(&s, &signalable::foo); 
    t("world"); 
} 

至于一些在你的代码更具体的错误,其中大部分似乎都与你的typedef。 C++ 11允许“模板类型定义”,但它们看起来不是那样。看看这个线程模板类型定义的例子:

C++ template typedef

+0

你的代码是正确的。只需将'fun'和构造函数的'typeT :: trig'改为'trig'即可解决它。谢谢。 – Haix64 2012-04-21 11:36:40