我明白为什么 member template functions cannot be virtual ,但我不确定最好的解决方法是什么。
我有一些类似的代码:
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;
}
};
显然,我需要动态调度。但考虑到这些类实际上非常大,我不想为整个类 制作模板。而且我仍然希望支持任何类型的迭代器。
实现此目标的最佳方法是什么?
最佳答案
如果支持任何类型的迭代器是您唯一想要的,您可以使用使用类型删除的迭代器。我认为在 Boost Sandbox/Vault 或 Adobe Labs 或其中之一中的某处实现了 any_iterator
。这是 Google 的第一个结果:
http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html
关于c++ - 成员模板函数不能是虚拟的 - 解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8099877/