Re: Why no virtual member templates?
On Mar 31, 8:42 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
Tom Craig wrote:
A few times recently I've wanted to use a virtual member
template, like this:
struct A {
template<class T> virtual void f();
};
Unfortunately, the C++ standard forbids this. I'm a bit
confused about this: Why should virtual member templates be
forbidden?
A::f isn't a function, it's a function template.
Yes, but each specialization is a function. And the code you
write to implement it does look a lot like that you'd write in a
function.
Do you mean that you would like to generate a separate virtual
function for each instantiation of f?
That's what it would mean, wouldn't it. Each specialization of
f is a separate virtual function.
How would you ever override f?
The same way you override any virtual function, no. A function
template with the same signature in the derived class.
(I suppose you could declare struct B: A { template<class T>
virtual void f(); };, with the proviso that instantiations of
B::f override matching instantiations of A::F, but that seems
like a maintenance nightmare waiting to happen.)
In the simpler cases (no explicit specialization), I don't see
where it would cause the user any more problems that a normal
virtual function. (On the other hand, just specifying what
happens if there are explicit specializations for some of the
cases sounds like a major problem to me.)
The real reason we don't have it, however, is that no one could
figure out how to reasonably implement it. If you use dynamic
linking, for example, it would mean that the dynamic linker
would have to be able to instantiate templates; if you used a
sub-table of the vtable, as the original poster suggested, the
dynamic linker would have to be able to find all of the existing
vtables for the class, and increase the size of this subtable.
Even without dynamic linking, the linker would still have to
work out which instantiations were needed: you'd need an
instantiation of Derived::f< int >, for example, if anyone calls
Base::f< int > in a polymorphic manner (through a pointer or a
reference).
virtual member templates would be *sooo* very useful.
For what, exactly? Templates are compile-time entities,
whereas virtual functions exist specifically to support
run-time indirection.
Still, it's a rare program that doesn't use both, at various
times. And once or twice I've found that they would have been
convenient, if they'd have been available.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34