在c#中(至少使用。net,但我认为它是通用的),您可以像这样创建事件:
c++是否有类似的机制?
PS:我从来都不喜欢信号/插槽系统,所以请不要建议它,因为我已经在使用它,并希望切换到其他东西
c#中的事件机制实际上只是观察者模式的正式语言实现版本。这种模式可以用任何语言实现,包括c++。有很多c++实现的例子。
最大和最常见的实现可能是Boost。信号和增强。Signals2,虽然你明确提到不喜欢信号/插槽风格的实现。
Event.h可以从下面的链接下载,它提供了一个类似于。net的事件在c++中实现:http://www.codeproject.com/Tips/1069718/Sharp-Tools-A-NET-like-Event-in-Cplusplus
用法示例:
#include "Event.h" // This lib consists of only one file, just copy it and include it in your code.
// an example of an application-level component which perform part of the business logic
class Cashier
{
public:
Sharp::Event<void> ShiftStarted; // an event that pass no argument when raised
Sharp::Event<int> MoneyPaid; // will be raised whenever the cashier receives money
void Start(); // called on startup, perform business logic and eventually calls ProcessPayment()
private:
// somewhere along the logic of this class
void ProcessPayment(int amount)
{
// after some processing
MoneyPaid(amount); // this how we raise the event
}
};
// Another application-level component
class Accountant
{
public:
void OnMoneyPaid(int& amount);
};
// The main class that decide on the events flow (who handles which events)
// it is also the owner of the application-level components
class Program
{
// the utility level components(if any)
//(commented)DataStore databaseConnection;
// the application-level components
Cashier cashier1;
Accountant accountant1;
//(commented)AttendanceManager attMan(&databaseConnection) // an example of injecting a utility object
public:
Program()
{
// connect the events of the application-level components to their handlers
cashier1.MoneyPaid += Sharp::EventHandler::Bind( &Accountant::OnMoneyPaid, &accountant1);
}
~Program()
{
// it is recommended to always connect the event handlers in the constructor
// and disconnect in the destructor
cashier1.MoneyPaid -= Sharp::EventHandler::Bind( &Accountant::OnMoneyPaid, &accountant1);
}
void Start()
{
// start business logic, maybe tell all cashiers to start their shift
cashier1.Start();
}
};
void main()
{
Program theProgram;
theProgram.Start();
// as you can see the Cashier and the Accountant know nothing about each other
// You can even remove the Accountant class without affecting the system
// You can add new components (ex: AttendanceManager) without affecting the system
// all you need to change is the part where you connect/disconnect the events
}
如果boost不是一个选项,我在这里用c++实现事件。语义几乎与。net中的相同。这是一个紧凑的实现,但使用了相当先进的c++特性:需要一个现代的c++ 11编译器。