C # -like events in C ++, composition

Over the past couple of months I have used C # a lot and am used to events and delegates. It is very easy to use in your classes, just use events to receive messages from the component ... Now I'm trying to do something like this in C ++ and I don’t know how to do it.

How is composition performed in C ++? The only way that comes to my mind is inheritance ... do you exit the class and redefine its functions in order to receive data from it? Is there any other way (better)?

More details

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 ++ ...

+3
source share
5 answers

( ). , std::function< return(args..) >, , , , - ..

+4
+4

#:

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 - - ++ 0x ( ) #. , , GBL ( - ++, ).

+2

++:

  • ( , +/- ) → , .
  • public Inheritance,
  • .
0

FastDelegates.

“You can imagine that [delegates] are a high-level concept that is not easily implemented in assembly code. This is clearly not the case: calling a delegate is essentially a very low-level concept and can be as low a -level (and fast) as usual function call: The C ++ delegate just needs to contain this pointer and a simple pointer to the function.

0
source

Source: https://habr.com/ru/post/1780678/


All Articles