This is a mirror of official site: http://jasper-net.blogspot.com/

MFC Delagates

| Sunday, March 20, 2011
Introduction

The arrival of .NET brought some very nice approaches and techniques. Of course, one main reason of .NET code efficiency (I mean from a developer's scope) is that .NET languages are fully and exclusively object oriented.

One very nice attribute of .NET (and especially of C#) is delegates. Delegates are defined as member variables, and can hold references to functions.

Can C++ (and I meal real (native) C++) simulate this approach? While I am developing a very nice project in MFC, I realized that I can do (or even simulate) everything (with C++) that all other languages do. The only thing that I have noticed C++ does not have are function definitions in functions, as Delphi and Pascal have.

Anyway, because I wanted to get rid of non object oriented event handlings that MFC have (DECLARE MAPS... etc.), I tried to develop a template class that simulates C# delegates. And it wasn't so difficult.

The Class

The class is as follows:

//
// 
template <class FP, class SENDER,
class ARG1=int, class ARG2=int, class ARG3=int, class ARG4=int,
class ARG5=int, class ARG6=int, class ARG7=int, class ARG8=int>
class GDDelegateS
{
public:
    struct FPDATA
    {
        FP fp; //function pointer
        void *data;
    };
public:
    GDDelegateS()
    {
        m_List = NULL;
        m_ListCount = 0; 
    }
    virtual ~GDDelegateS()
    {
        Clear();
    }
protected:

    FPDATA *m_List;
    int m_ListCount;
public:
    void Add(FP funct, void *data)
    {
        FPDATA *nList = new FPDATA[m_ListCount+1];
        FPDATA *f=NULL;
        for(int i=0;i<m_ListCount;i++)
        {
            if(funct==m_List[i].fp && data == m_List[i].data)
            {
                delete []nList;
                return;
            }
            nList[i].data = m_List[i].data;
            nList[i].fp = m_List[i].fp;
        }
        nList[i].data = data;
        nList[i].fp = funct;
        if(m_List)
        delete m_List;
        m_List = nList;
        m_ListCount++;
    }

Read more: Codeproject

Posted via email from Jasper-net

0 comments: