我正在尝试使用示例用法实现观察者模式,如下所示:
class Widget
{
class WidgetObserver
{
virtual void SomethingHappened(Widget&) { };
virtual void TextChanged(Widget&, const char*) { };
virtual void BoundsChanged(Widget&, const Rect&) { };
}
void AddObserver(WidgetObserver& observer)
{
observers.Add(observer);
}
virtual void OnSomthingHappened()
{
observers.Fire(&WidgetObserver::SomethingHappened, *this);
}
virtual void OnTextChanged(const char* text)
{
observers.Fire(&WidgetObserver::TextChanged, *this, text);
}
// Same for OnBoundsChanged(const Rect&)
ObserverList<Widget> observers;
}
class AnotherWidget : WidgetObserver
{
virtual void SomethingHappened(Widget& widget) override
{
std::cout << "Something happened with " widget.name() << std::endl;
}
// Implementations for TextChanged and BoundsChanged ...
}
void main()
{
Widget w;
AnotherWidget aw;
w.AddObserver(aw);
w.OnSomethingHappened();
}
现在我ObserverList
的当前(部分)实现是:
template <typename TObserver>
class ObserverList
{
std::vector<TObserver*> observer_list;
void AddObserver(TObserver& observer) { observer_list.push_back(&observer); }
template <typename ...TArgs>
void Fire(void(TObserver::*func)(TArgs...), TArgs&& args)
{
for (TObserver* ob : observer_list)
{
(ob->*func)(std::forward<TArgs>(args)...);
}
}
}
这可以按预期使用函数SomethingHappened
和BoundsChanged
,它们都通过引用而不是值传递所有参数,但TextChanged
参数之一(const char* text
})通过值而不是引用传递。当我将其更改为const char*& text
时,它会编译,但不能使用MSVC ++ 14.1(Visual Studio 2017)进行编译
error C2672: 'ObserverList<Widget::WidgetObserver>::Fire': no matching overloaded function found
error C2782: 'void ObserverList<Widget::WidgetObserver>::Fire(void (__thiscall Widget::WidgetObserver::* )(TArgs...),TArgs &&...)': template parameter 'TArgs' is ambiguous
好像编译器不喜欢通过值传递的参数,有没有办法让它像它们一样?
答案 0 :(得分:1)
您可以声明func
有一个简单类型F
,即
template <typename F, typename ...TArgs>
void Fire(F func, TArgs&&... args);