
On Thu, Feb 12, 2009 at 3:56 AM, Ravi <lists_ravi@lavabit.com> wrote:
On Wednesday 11 February 2009 13:27:46 Gokulakannan Somasundaram wrote:
As you all know, there are situations, wherein the virtual function usage can be replaced with templates. But virtual functions can never be used with templates, since all the instantiations have to be tracked to form the virtual function table. But we can ask the user to provide a typelist of classes, that would probably be used with the
virtual
template function. I think this would solve this issue for most of the cases.
If the list of arguments/return types is known at compile time, is this not the same as overloaded virtual functions? Here's an example:
#include <iostream> using namespace std; struct Base { virtual void func( int ) { cout << "Base::int overload" << endl; } virtual void func( double ) { cout << "Base::double overload" << endl; } template <typename T> void virtfunc( T x ) { func( x ); } // "virtual" virtual ~Base() {} }; struct Derived : Base { virtual void func( int ) { cout << "Derived::int overload" << endl; } virtual void func( double ) { cout << "Derived::double overload" << endl; } virtual ~Derived() {} };
int main( int, char *[] ) { Base *p = new Derived; p->virtfunc( 3 ); p->virtfunc( 3.14 ); }
$ g++ -o out -Wall tempvirt.cc $ ./out Derived::int overload Derived::double overload
Regards, Ravi
I think, i am trying to accomplish, what you have done through overloading through templates. Say if you have 10 such functions, with each implementation being different in the inheritance hierarchy, then you will write the same piece of code again and again, with different types. In your example you have written the functions twice, which is redundant. (same piece of code repeated twice). More overhead on maintenance,as the number of overloads increase. Hope i am able convey my point. Thanks, Gokul.