|
-
July 6th, 2012, 11:20 AM
#4
Re: template function
 Originally Posted by mce
I declared a template function in my .h file, but it doesn't seem to be able to take virtual.
It's not clear from your code what you are actually trying to show.
Non-member functions cannot be virtual.
Template member functions also cannot be virtual. This is because a template (member) function actually defines a "family" of functions. Virtual functions work (in all known C++ compilers AFAIK) by storing a so-called vtable that stores pointers to the member functions that are resolved at run-time when a virtual function is called. When you instantiate a derived class, it will set the function pointer in the vtable to the overridden member function. That's a concept that cannot be scaled to a (possibly infinite) family of functions. Thus, template member functions cannot be virtual. For the same reason you also cannot take a pointer to a template function.
What is possible is what monarch_dodra mentioned, i.e. a template class can have a virtual (non-template) member function. Something like this
Code:
template <class T>
struct Base
{
virtual ~Base() {}
virtual T Foo() { return T(); }
};
struct Derived : public Base<int>
{
virtual int Foo() { return 1; }
};
Last edited by D_Drmmr; July 6th, 2012 at 11:23 AM.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|