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?
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_iteratorimplemented 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