CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #1
    Join Date
    Mar 2008
    Posts
    38

    templates and function callbacks

    This is a bit convoluted...
    There is existing code for an observer pattern. There is a data repository class. There is a data observer super class with an update() function. Usually I derive from the data observer and call attach on the data I want to observe. When the data repository updates the data it will call the update() function on my observer class. The code sorta looks like this.
    Code:
    class DataObserver
    {
    public: 
        virtual void Update()=0;
    }
    
    class DataClass
    {
    public: 
        void Attach(DataObserver * obs);
    }
    
    class DataRepository
    {
       DataClass data[somelength];
    }
    to use that code I do the following:
    Code:
    class MyObserver : public DataObserver
    {
    public:
    MyAlgoClass* algoClassPtr;
    MyObserver (MyAlgoClass* myClass);
    virtual void Update();
    }
    
    void MyObserver ::Update(void) {
    DataType data;
    data = static_cast<DataType>(dataPtr->GetData());
    
    algoClassPtr->SomeRandomFunction(data);
    }
    So that all works fine. My only issue is that I got to create a lot of "MyObserver" classes each time I want to observe a specific data field. And I will observe the same field in multiple address spaces. So I'd like to make MyObserver a template. I am not allowed to change the old observer pattern code :/

    So here is my templete so far:
    Code:
    template <typename DataType, fieldId FieldId> class GenericObserver : public DataObserver
    {
    public:
    MyAlgoClass* algoClassPtr;
    MyObserver (MyAlgoClass* myClass);
    virtual void Update();
    }
    
    template <typename DataType, fieldId FieldId> void GenericObserver<FieldType, FieldId> ::Update(void) {
        DataType data;
        
        data= static_cast<DataType >(dataPtr->GetData());
            
        algoClassPtr->SomeRandomFunction(data);
     
    }
    So the porblem lies in MyAlgoClass* algoClassPtr; That class can be different for every observer class I might have. So I believe i need something like a callback pattern. Which I could probably figure out, but having a template is making it hard to figure out the best way to do it. So what is the best way to have my observer template have the ability to call any random function from any class?

    Let me know if something isn't clear as I skipped around trying to make this short.
    Last edited by sdcode; July 8th, 2009 at 10:44 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured