开发者

C#-like events in C++, Composition

开发者 https://www.devze.com 2023-01-31 10:24 出处:网络
For the last couple of months I\'ve been using C# a lot and got used to events and delegates. Its is very easy to use composition in your classes, just use events to get messages from the component...

For the last couple of months I've been using C# a lot and got used to events and delegates. Its is very easy to use composition in your classes, just use events to get messages from the component... Now I'm trying to do something similar in C++ and don't know how to do it.

How is composition done in C++? The only开发者_Python百科 way that comes to my mind is inheritance... you derive from the class and override its functions to receive input from it? Is there any other easier (better) way?

To further explain...

I want to write a reusable component like this...

public delegate void OnDataReceivedHanlder(byte[] data);
public class TcpConnection
{
    public void Connect(string iP, ushort port);
    public void Send(byte[] data);
    public event OnDataReceivedHandler OnDataReceived;    
}

in C++...


Typically, you will use inheritance (either dynamic or static) for this. Alternatively, you would just use a std::function< return(args..) >, which can be bound to a number of alternatives, like function objects, function pointers, lambda functions, etc.


Yes, take a look at boost::signals2 . You can use boost signals to connect signals to multiple slots, just like events in C#. The tutorials and examples on the page I linked should be helpful.


Here is an equivalent to your C# code:

class TcpConnection
{
public:
    void Connect(const std::string& iP, unsigned port);
    void Send(const std::vector<unsinged char>& data);
    std::function<void (const std::vector<unsinged char>&)> OnDataReceived;
};

std::function and lambda functions are C++0x (more powerful) equivalents to C# delegates. If you need more complex multicast facilities with threads and fibers and synchronous and asynchronous event handlers, look at GBL library (it also allows you to create event-driven designs graphically and will generate C++ code for you, so you don't need to write it by hand).


I can think of three ways of composition in C++:

  1. Aggregation (adding a delegate member, +/- similar to private inheritance) -> to be preferred.
  2. public Inheritance,
  3. using the composite Design Pattern for really complex structures.


Have a look over FastDelegates too.

"You might imagine that [delegates] are a high-level concept that is not easily implemented in assembly code. This is emphatically not the case: invoking a delegate is intrinsically a very low-level concept, and can be as low-level (and fast) as an ordinary function call. A C++ delegate just needs to contain a this pointer and a simple function pointer."

0

精彩评论

暂无评论...
验证码 换一张
取 消