既然代码胜于雄辩,你会用这个:
struct StringEvent
{
const void* source;
const std::string str;
StringEvent(const void* source, const std::string& str)
: source(source), str(str)
{ }
};
class StringEventListener
{
public:
virtual void handler(const StringEvent& event) = 0;
}
class Test : public StringEventListener
{
public:
void handler(const StringEvent& event)
{
std::cout << event.str << std::endl;
}
}
class EventSource
{
public:
EventSource(StringEventListener* listener)
{
listener->handler(StringEvent(this, std::string("foo")));
}
}
int main()
{
Test test;
EventSource(&test);
}
在这个?
class Test
{
public:
void handler(const std::string& str)
{
std::cout << str << std::endl;
}
};
class EventSource
{
public:
EventSource(const boost::function<void (const std::string&)>& funcPtr)
{
funcPtr(std::string("foo"));
}
};
int main()
{
Test test;
EventSource(boost::bind(&Test::handler, &test, _1));
}
使类 EventSource 调用test.handler("foo")
?
来自 Java/C# 世界,我发现第一种方法更直观,虽然很冗长,但是否建议在现实生活中使用,还是会导致比其价值/性能损失更多的问题?