I have a 开发者_JAVA百科base class that I made a template because I want to vary the type it takes for several functions, but I want to derive from these templated base classes. I want to store a vector of these classes. My idea was to create a non-templated base class above everything in the hierarchy, and use double dispatching to figure out the type. Am I doing this the "right way"?
Here's a code snippet of the scenario:
class FooBase
{
public:
virtual void Accept( Visitor &v );
};
template<class T>
class Foo : public FooBase
{
public:
virtual void DoThing( const T & );
virtual void Accept( Visitor &v) = 0;
};
template<>
class Foo<Bar> : public FooBase
{
public:
virtual void Accept( Visitor &v )
{
v.HandleBar( *this );
}
};
template<>
class Foo<Baz> : public FooBase
{
public:
virtual void Accept( Visitor &v )
{
v.HandleBaz( *this );
}
};
// and many derived classes from Foo, Foo
Then in another class
class Visitor
{
public:
virtual void HandleBar( Foo<Bar> &f ) = 0;
virtual void HandleBaz( Foo<Baz> &f ) = 0;
};
class Manager : public Visitor
{
public:
void AddFoo( FooBase& f )
{
a.push_back( f );
}
void RunAll()
{
for ( std::vector<std::shared_ptr<FooBase> >::iterator it = a.begin(); it != a.end(); ++it )
{
(*it)->Accept( *this );
// do common action that doesn't depend on types
}
}
virtual void HandleBar( Foo<Bar> &f )
{
Bar item = GetBarItemFunction(); // not shown
f.DoThing( item );
}
virtual void HandleBaz( Foo<Baz> &f )
{
Baz item = GetBazItemFunction(); // not shown
f.DoThing( item );
}
private:
std::vector<std::shared_ptr<FooBase> > a;
};
I just don't know if this is the "best" way to do it. I could use dynamic_casting, but that feels dirty. So is this a solid solution to the situation? Please advise (I hope I didn't leave any glaring syntax errors in the example)
(EDIT removed, was stupid error on my part)
I think you've almost got it. I would write the visitor class like:
class Visitor
{
public:
virtual void HandleFoo( Foo<Bar> &f ) = 0;
virtual void HandleFoo( Foo<Baz> &f ) = 0;
//default implementation for unknown Foo types:
virtual void HandleFoo( FooBase &f ) = 0;
};
Now you don't need to specialize your templated Foo class and you can just write the following to work with all class T's your application may need. The correct overloaded HandleFoo function will be chosen based on the template type used in Foo. You will still have to add methods to your visitor class to avoid the default behavior being invoked.
template<class T>
class Foo : public FooBase
{
public:
virtual void DoThing( const T & );
virtual void Accept( Visitor &v) {
v.HandleFoo( *this );
};
};
精彩评论