Storing vector of std::shared_ptr<Foo> where Foo is a templated class

心不动则不痛 提交于 2019-12-06 00:37:08

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 );
    };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!