Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an interface for an abstract class template in C++

I have the code as below. I have a abstract template class Foo and two subclasses (Foo1 and Foo2) which derive from instantiations of the template. I wish to use pointers in my program that can point to either objects of type Foo1 or Foo2, hence I created an interface IFoo.

My problem is I'm not sure how to include functionB in the interface, since it is dependant on the template instantiation. Is it even possible to make functionB accessible via the interface, or am I attempting the impossible?

Thank you very much for your help.

class IFoo {     public:         virtual functionA()=0;  };  template<class T> class Foo : public IFoo{     public:         functionA(){ do something; };         functionB(T arg){ do something; }; };  class Foo1 : public Foo<int>{ ... };  class Foo2 : public Foo<double>{ ... }; 
like image 572
bishboshbash Avatar asked Jul 15 '10 00:07

bishboshbash


1 Answers

You are actually attempting the impossible.

The very heart of the matter is simple: virtual and template do not mix well.

  • template is about compile-time code generation. You can think of it as some kind of type-aware macros + a few sprinkled tricks for meta programming.
  • virtual is about runtime decision, and this require some work.

virtual is usually implemented using a virtual tables (think of a table which lists the methods). The number of methods need be known at compile time and is defined in the base class.

However, with your requirement, we would need a virtual table of infinite size, containing methods for types we haven't seen yet and that will only be defined in the years to come... it's unfortunately impossible.

And if it were possible ?

Well, it just would not make sense. What happens when I call Foo2 with an int ? It's not meant for it! Therefore it breaks the principle that Foo2 implements all the methods from IFoo.

So, it would be better if you stated the real problem, this way we could help you at a design level rather than at a technical level :)

like image 94
Matthieu M. Avatar answered Oct 05 '22 10:10

Matthieu M.