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>{ ... };
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With