0

Is it possible to achieve in C++ similar behavior to that of events with custom arguments in C#?

I came across the following link:

https://www.tangiblesoftwaresolutions.com/articles/cplus_equivalent_to_csharp_events.html

Can that idea be applied to a situation where custom event args are used?

An example of C# code to be mimicked or implemented in C++ is below. For context, this is part of an (WinForms) application using the MVC architecture pattern.

// part of service layer of Model
// the View is subscribed to this class
public static class ModelService
{
    // methods for using data access layer to interact with database...

    // event for getting all customers
    public static event EventHandler<GetAllCustomersEventArgs> OnGetAllCustomers = delegate { };

    // custom event args
    public class GetAllCustomersEventArgs : EventArgs
    {
        private List<Customer> customerList;

        // ctor
        public GetAllCustomersEventArgs(List<Customer> customerList)
        {
            this.customerList = customerList;
        }

        public List<Customer> getList()
        {
            return this.customerList;
        }
    }
}

// part of View
// subscribed to Model
public partial class ViewCustomersForm : Form
{
    public ViewCustomersForm
    {
        // subscribe to the required Model events
        CustomerOps.OnGetAllCustomers += new EventHandler<GetAllCustomersEventArgs>(customerEventHandler);
    }

    private void customerEventHandler(object sender, GetAllCustomersEventArgs e)
    {
        populateView(e.getList());
    }
}

The idea is to implement this in a WxWidgets application in the future.

I understand that in C++, function pointers are equivalent to the use of delegates in C#. However, I am unfamiliar with the concept of function pointers, and seeking some guidance on how to use them in the context of what is desired to be achieved as described above, with perhaps some example code.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Al2110
  • 566
  • 9
  • 25
  • Can you please clarify what problems you are facing in your implementation? "Pointer to function that takes arguments of a particular type" was there in C/C++ since very first versions... Or you are asking about something else altogether? – Alexei Levenkov Apr 19 '20 at 02:41
  • @AlexeiLevenkov I looked at the example in the link, but it was not clear to me how to implement it with custom args. I understand that in C++, function pointers are equivalent to delegates in C#, but I am not familiar with the use of function pointers, as I only have very basic C++ knowledge, coming from a C# background. I shall add this information to the post. – Al2110 Apr 19 '20 at 02:45

0 Answers0