Storing the vector std :: shared_ptr <Foo>, where Foo is the template class

I have a base class that I created for a template because I want to change the type that is required for several functions, but I want to extract from these template base classes. I want to save the vector of these classes. My idea was to create a non-template base class above everything else in the hierarchy and use dual dispatch to determine the type. Am I doing this "right"?

Here is a snippet of script code:

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 it seems dirty. So is this a solid solution to the situation? Please report (I hope that in this example I did not leave glaring syntax errors)

(EDIT removed, there was a stupid mistake on my part)

+3
source share
1 answer

I think you almost figured it out. I would write a class of visitors, for example:

 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 template class Foo, and you can simply write the following to work with the entire T class, which might require your application. The correct overloaded HandleFoo function will be selected based on the type of template used in Foo. You still have to add methods to your visitor class in order to avoid the default behavior invoked.

 template<class T> class Foo : public FooBase { public: virtual void DoThing( const T & ); virtual void Accept( Visitor &v) { v.HandleFoo( *this ); }; }; 
+3
source

All Articles