c++c++builder-10.2-tokyo

How do I pass a TForm (this) generically?


I have two almost identical forms (Form4 and Form5) that have several common items but handle different data. I am trying to write a helper function that will take either of these forms.

Both forms are created dynamically.

So far I am able to write the function that processes the data from Form4 [Process(TForm4 *F)]. I cannot do the same from Form5 because the helper function is specific to TForm4.

From Form4

 Edit1Exit(Tobject *Sender){     
   Process(this);
 }

From Form5

 Edit1Exit(Tobject *Sender){     
   Process(this);
 }

 Process(TForm4 *F){
  // Do something like F->BitBtn1->Visible=false;
  }

The problem is that Process( ) is written for TForm4 so it won't accept TForm5.

How do I declare Process() so that it will take either form.


Solution

  • In general, you will have three options:

    1. Write an explicit overload for each version, and duplicate the code. I.e.,
    void Process(TForm4* F) {
       /// do things
    }
    
    void Process(TForm5* F) {
       /// do things
    }
    
    
    1. Derive from a common base class that declares a virtual interface, i.e.,
    class TFormBase {
        // common virtual interface, and a virtual destructor
    };
    
    class TForm4 : public TFormBase {
        // implementation of the interface + data members
    };
    
    class TForm5 : public TFormBase {
        // implementation of the interface + data members
    };
    
    void Process(TFormBase* F) {
        // interact with F via the virtual interface
    }
    
    
    1. Use templates (but in that case, the implementation of your function has to be accessible where it is used; usually that means it has to live in the header file or in a file that can be included directly), i.e.,
    template<typename T>
    void Process(T* F) {
        // interact with the classes; assumes a common interface
    }
    
    

    For simplicity, I've omitted a lot of details, but this should get you started.