I have a 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)