Re: pure virtual template...
mathieu wrote:
Hi there,
I don't think I'll be able to describe my issue correctly, so
instead I'll just give a pseudo C++ code I am struggling with.
Basically I am looking for a 'pure virtual template' function that I
would be able to declare in the base class (*).
As most compilers implement virtual method by means of virtual method tables,
declaring a template member virtual is not allowed (sorry that I cannot cite the
paragraph of the C++ standard). Were it not so, the size of the VMT table could
not be determined by the compiler (it cannot predict how many instantiations of
the template member could be needed in the following code). Thus templates and
virtual methods don't go together.
> (*)
> struct Base
> {
> };
>
> struct A : public Base
> {
> template <typename T> void foo() {}
> };
>
> struct B : public Base
> {
> template <typename T> void foo() {}
> };
>
> int main(int argc, char *argv[])
> {
> Base * base;
> if( argc )
> {
> base = new A;
> }
> else
> {
> base = new B;
> }
> base->foo<int>();
> return 0;
> }
>
I think you mixed up two more or less orthogonal concepts of the C++ programming
language: templates are used to reuse code where the logic is known at compile
time (that means you know exactly what your code will do when you compile the
code), whereas virtual methods are used to reuse code whose semantics will be
determined at run-time. If you know at compile time that each class A and B will
have a foo implementation with template parameter int, you may do the following:
struct Base
{
virtual void foo_int () = 0;
};
struct [A and likewise B] : public Base
{
template <typename T> void foo() {}
virtual void foo_int ()
{
foo<int> ();
}
};
int main(int argc, char *argv[])
{
:
base->foo_int();
return 0;
}
Note that there are two different resolution mechanisms involved: template
programming uses the determination with instantiation of a template function
should be used (the proper template argument is deduced), whereas virtual
methods employ a resolution mechanism involving VMTs: this table decides at
run-time which method should be invoked. You are trying to get both mechansims
working in a single step. For above mentioned reasons, this won't work.
Regards,
Stuart