Boost logo

Boost :

Subject: Re: [boost] Request For a feature - Templated virtual functions
From: Gokulakannan Somasundaram (gokul007_at_[hidden])
Date: 2009-02-12 01:47:53


>
>
> b) I have a multi-method design pattern, where in i need more than one
>> run-time resolution through the virtual functions.
>>
>
> Boost.Variant supports that.
>
> Thanks for pointing me to Boost.Variant. But let me just try to clarify my
understanding on Boost Variant. It is a kind of union data type, where we
store the data and its type together. Whenever we retrieve the data, it does
a switch-case lookup and type-casts the data to that type. In my opinion,
the switch-case is equivalent to a virtual table lookup. They should be
having more or less the same runtime penalty. Infact if we have more virtual
functions, it is better to go with the virtual table lookup. So for avoiding
a virtual function call, we are introducing a virtual function call like
penalty.

I would just like to write some code to explain my case in more detail.

Class Base1
{
public:
         virtual void run1(int context) { std::cout << "Base1 Run1"<<
context; }
         virtual void run2(int context) { std::cout << "Base1 Run2"<<
context; }
};

Class Derived1 : public Base1
{
public:
       virtual void run1(int context) { std::cout << "Derived1 Run1"<<
context; }
       virtual void run2(int context) { std::cout << "Derived1 Run2"<<
context; }
};

class Base2
{
public:
      virtual void run(Base1* base1, int context) { base1->run1(context); }

};

Class Derived2 : public Base2
{
public:
      virtual void run(Base1* base1, int context) { base1->run2(context); }

};

int main()
{
      Base2* a = new Base2;
      Derived1* b = new Derived1;
     int context =2;
      a->run(b, context);
};

Here even though, i know the type information of b, i am losing it. I can
maintain it by function overloading, where in, i would repeat the same code
for each overload. It would be much more elegant to achieve it with
templates.

Thanks,
Gokul.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk