0

我正在使用示例http://www.codeproject.com/Articles/3267/Implementing-a-Subject-Observer-pattern-with-templ来实现模板化的主题/观察者模式。但是,我遇到了令人讨厌的编译错误,看起来继承不起作用,或者奇怪的演员表。任何帮助都会很棒。帖子底部是导致问题的行。

错误

FooManager.h: In member function
    'ReturnEnum FooManager::AddBar(BarPtr)':

Foo.h:150: error: no matching function for call to
    'Bar::attach(FooManagerPtr)'

Subject.h:23: note: candidates are: 
    void Subject<T>::attach(Observer<T>) [with T = boost::shared_ptr<Bar>]

编码

类型.h

class Bar;
typedef boost::shared_ptr<Bar> BarPtr;

class FooManager;
typedef boost::shared_ptr<FooManager> FooManagerPtr;

观察者.h

#include "types.h"
template <class T>
class Observer
{
    public:
        Observer(){}
        virtual ~Observer() {}
        virtual void update(T subject) = 0;
};

主题.h

#include "types.h"
template <class T>
class Subject
{
    private:
        vector< Observer<T> > m_observers;

    public:
        Subject() {}
        virtual ~Subject() {}
        void attach(Observer<T> observer)
        {
            m_observers.push_back(observer);
        }

        void notify()
        {
            for(vector< Observer<T> >::iterator it = m_observers.begin(); it != m_observers.end(); ++it)
            {
                (*it)->update(static_cast<T>(this));
            }
        }
};

酒吧.h

#include "types.h"
class Bar             : public Subject<BarPtr>
{
};

FooManager.h

#include "types.h"
class FooManager                : public Observer<BarPtr>
{
    public:
        ReturnEnum AddBar(BarPtr pBar)
        {
            pBar->attach( FooManagerPtr(this, boost_null_deleter()) );
        }
};
4

2 回答 2

1

根据您想要实现的目标,您可以尝试更改(警告,未经测试的代码!):

    void attach(Observer<T> observer)
    {
        m_observers.push_back(observer);
    }

    void attach(boost::shared_ptr<Observer<T>> observer)
    {
        m_observers.push_back(observer);
    }

vector< Observer<T> > m_observers;

vector< boost::shared_ptr<Observer<T> > > m_observers;
于 2012-07-16T15:59:03.767 回答
1

pBar指向Bar实例,所以attach()期望Observer<BarPtr>,而您通过shared_ptr<Observer<BarPtr> >

(顺便说一句,如果您已经使用了 boost,那么使用 Boost.Signals2 不是更好吗?)

于 2012-07-16T16:00:52.710 回答