繁体   English   中英

通过继承和模板进行static_pointer_cast

[英]static_pointer_cast through inheritance and template

我在寻找以下错误时遇到了麻烦,这些错误是在编译std::static_pointer_cast<>()时抛出的:

error: invalid static_cast from type ecse::EventSubscriptionManager<ecse::BaseEvent>* to type ecse::EventSubscriptionManager<TestEvent>*

我有以下层次结构。 最后,它们将充满POD类型的成员,并且很可能成为结构。

class BaseEvent {};

template <class E>
class Event : public BaseEvent, public Type<E> {};

class TestEvent : public Event<TestEvent> {};

我目前正在使用EventManager的Subscribe函数,但是在编译时我收到了上面发布的错误。 注意: E::ID()在类中定义为Type,用于标识类类型。

template <class E>
class EventSubscriptionManager
{
public:
  void Subscribe(std::function<void(E)>  fptr);
private:
  std::function<void(E)> event_function_;
};

class EventManager
{
public:
  template <class E>
  void Subscribe(std::function<void(E)> fptr)
  {
     std::shared_ptr<EventSubscriptionManager<E>> sub_manager_ptr;
     auto sub_manager_iterator = sub_managers_.find(E::ID());
     if(sub_manager_iterator == sub_managers_.end())
     {
       sub_manager_ptr = std::make_shared<EventSubscriptionManager<E>>();
     }
     else
     {
       sub_manager_ptr = std::static_pointer_cast<EventSubscriptionManager<E>>(sub_manager_iterator->second);
     }
     // Continue function...
  }
private:
  std::unordered_map<std::size_t, std::shared_ptr<EventSubscriptionManager<BaseEvent>>> sub_managers_;
}

我认为问题在于,在TestEventBaseEvent存在带有模板的Event<E>类,其中TestEvent继承了Event<TestEvent>而不是BaseEvent 这是真的? 如果是这样,我如何设置层次结构以允许这种类型的转换?

如果不是这种情况,那么上面的静态转换有什么问题?

在C ++中,即使在BaseSub之间不存在协方差或对立关系, T<Base>T<Sub>之间也没有关系。

您要么需要构建不同EventSubscriptionManager实例的公共祖先(例如: EventSubscriptionManagerBase ),然后使用它,要么提供转换构造函数。

我可以告诉你为什么它不能编译。 这是因为

EventSubscriptionManager<E>

与...无关

EventSubscriptionManager<BaseEvent>

因此,根据参考页上的第1.)点

static_cast<EventSubscriptionManager<E>*>((EventSubscriptionManager<BaseEvent>*)nullptr)

格式不正确。

但是,在不了解背景的情况下,我无法说出解决方法。 公正:您必须将两个类联系起来,或者选择一个全新的设计。



为此, 是一个失败的最小示例,这可能会有所帮助:

struct Base {};
struct Derived : Base {};

template<typename T>
struct Foo {};

int main()
{
   static_cast<Foo<Derived>*>((Foo<Base>*)nullptr);
}

您可以尝试对此进行改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM