Search code examples
c++vtable

Is there a way to set the function pointer according to user parameter?


I have one version of code with benchmark surround with macros to enable or disable, and I want to change the code that I can turn on and off the benchmark settings without recompiling my code and without a lot of if-else or without code duplication (version with the benchmark and a version without)?

A way to set the vtable for the correct functions?

EDIT: added code sample for what I don't wont to do

EDIT V2 I understood from the answers that there isn't a way, so if I create two shared object can I code on run time to which one to link to?

#include <iostream>
#include <string>
using namespace std;

struct A
{

   virtual int add(int a,int b)=0;
};

struct B:public A
{
     virtual int add(int a,int b){return a+b;}

};

struct C:public A
{
     virtual int add(int a,int b)
     {
         cout << "time" << endl;
         return a+b;
         }

};


int main(int argc,char* argv[])
{
    A* a;
    string s(argv[1]);
    if(s.compare("t"))
    {
        a = new C;
    }
    else
    {
        a=new B;
    }
    cout << a->add(2,5);
    return 0;    
}

Solution

  • You are almost there. With the decorator pattern, you avoid code duplication. For the abstract class A a decorator printing the time would look like this:

    struct TimedA : public A
    {
         TimedA(A* base) : base_(base) {}
         virtual int add(int a,int b)
         {
             cout << "time" << endl;
             return base_->add(a, b);
         }
    
         A* base_;
    };
    

    The point of the decorator is that you can append it to any object of type A and it will inject the additional behavior.