I understand why member template functions cannot be virtual, but I'm not sure what the best workaround is.
I have some code similar to this:
struct Entity
{
template<typename It>
virtual It GetChildren(It it) { return it; }
};
struct Person : public Entity
{
template<typename It>
virtual It GetChildren(It it) { *it++ = "Joe"; }
};
struct Node : public Entity
{
Node left, right;
const char *GetName() { return "dummy"; }
template<typename It>
virtual It GetChildren(It it)
{
*it++ = left.GetName();
*it++ = right.GetName();
return it;
}
};
Clearly, I need dynamic dispatch. But given that the classes are actually pretty large, I don't want to template the entire class. And I still want to support any kind of iterator.
What's the best way to achieve this?
Member function templates can't be virtual functions. And, they can't override virtual functions from a base class when they're declared with the same name as a base class virtual function.
A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.
Templates provide static/compile time polymorphism. While virtualism provides dynamic polymorphism.
A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function.
If supporting any kind of iterator is the only thing you want, you may use an iterator that uses type erasure. I think there is an any_iterator
implemented somewhere in the Boost Sandbox/Vault or Adobe Labs or one of them. Here is the first result from Google:
http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html
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