jim
jim

Reputation: 691

Template version of virtual function calls from vector of objects

Is it possible to achieve something similar to the pseudo-code below via templates? If so what's the correct way to get proper compile-time polymorphism here? Thanks!

class Base {virtual void DoSomething();};
class Derived:public Base{void DoSomething();};
class Derived1:public Base{void DoSomething();};
class Derived2... etc.

std::vector<Base*> bases;
bases.push_back(new Derived());
bases.push_back(new Derived1());
etc...

bases[i]->DoSomething();

EDIT

since the above caused some confusion, i thought i should add an example of a proposed starting solution i just found that was given for a question similar to my own. this was pulled from an old australian linux c++ board from 2001 http://lists.linux.org.au/archives/tuxcpprogramming/2001-August/000135.html:

squareTy square;
twiceTy twice;
thriceTy thrice;

functionBaseTy* fns[] = { &square, &twice, &thrice };

template <class T, int N>
inline
void my_algorithm(T* functions[N])
{
 // This deduces T and the array size N
  my_real_algorithm(functions, N);
} 

template <class T> // not inline
void my_real_algorithm(T* functions, int n)
{
  // Loop here ...
}

Upvotes: 2

Views: 137

Answers (2)

masoud
masoud

Reputation: 56509

I suspect that is possible, How about below code?

std::vector<Base*> bases;
bases.push_back(new Derived());
bases.push_back(new Derived1());

//...

bases[i]->DoSomething();

Upvotes: 2

Preet Kukreti
Preet Kukreti

Reputation: 8617

If your container (vector) tracks a collection of base class instance pointers, you need to pay the standard vtable pointer/indirection per instance (or custom equivalent which is probably not worth the effort).

The possibility of statically eliminating vtable/function pointer overhead only presents itself when you know the concrete (derived) type at compile time.

Upvotes: 2

Related Questions