我正在尝试提供一个基类接口(请参阅:Accessor),它为所有派生类类型提供迭代器,但使用迭代器的模板特化,而不是运行时多态(即带有虚函数的派生迭代器)为它们迭代的容器类优化那些迭代器。 (迭代器将经常使用,我希望它们尽可能快。)
除此之外:我不需要迭代器与std库兼容,特别是因为迭代的项不能直接指向(operator *,operator->,operator []),因为它们有时会被返回Object类通过函数调用。
这是可能的,还是我不知道在派生类上使用派生迭代器类和虚拟迭代器运算符的开销?
目前我在声明基类接口时遇到了一个问题,因为我不知道如何允许我专门改变的类型,但仍然编写基类'iterator'typedef。< / p>
// base iterator template definition
template <class AccessorType,class ObjType>
class MyTypeIterator
:public std::iterator<std::forward_iterator_tag,ObjType,ptrdiff_t,ObjType*,ObjType&>
{
// this class should never be instantiated, only specialized flavors
};
// iterator template definition, specialized for ScalarAccessor
template <class AccessorType,class ObjType>
class MyTypeIterator<ScalarAccessor,Obj>
:public std::iterator<std::forward_iterator_tag,ObjType,ptrdiff_t,ObjType*,ObjType&>
{
// implements iterator interface using special knowledge of ScalarAccessor
};
// iterator template definition, specialized for ObjContainerAccessor
template <class AccessorType,class ObjType>
class MyTypeIterator<ObjContainerAccessor,Obj>
: public std::iterator<std::forward_iterator_tag,ObjType,ptrdiff_t,ObjType*,ObjType&>
{
// implements std::iterator interface using special
// knowledge of ObjContainerAccessor
};
class Obj { ... }; // my object class
class ObjContainer: public Obj { ... }; // an object that holds other objects
class Accessor
{
typedef MyTypeIterator<MyBase,Obj>::iterator;
virtual iterator begin( Obj *objPtr ) = 0;
virtual iterator end ( Obj *objPtr ) = 0;
virtual const char *niceName() const = 0; // other interface fns
};
// a helper class implementing an interface into the Obj class
ScalarAccessor: public Accessor
{
Accessor::iterator begin( *objPtr ) override
{
// I'd like to return how do return an instance of the specialized template
// MyTypeIterator<ScalarAccessor,Obj> here, but the following conflicts
// with the return type of Accessor::iterator.
// WON'T COMPILE
MyTypeIterator<ScalarAccessor,Obj> it( objPtr ); return it;
}
Accessor::iterator end( *objPtr ) override
{ /* same issue as in begin() */ }
virtual const char *niceName() const { return "Scalar";}
};
// a helper class implementing an interface into the ObjContainer class
ObjContainerAccessor: public Accessor
{
Accessor::iterator begin( *objPtr ) override
{
// I'd like to return how do return an instance of the specialized template
// MyTypeIterator<ObjContainerAccessor,Obj> here, but the following conflicts
// with the return type of Accessor::iterator.
// WON'T COMPILE
MyTypeIterator<ObjContainerAccessor,Obj> it( objPtr ); return it;
}
Accessor::iterator end( *objPtr ) override
{ /* same issue as in begin() */ }
virtual const char *niceName() const { return "Container";}
};