简体   繁体   English

更改设计以避免 dynamic_cast

[英]Changing design to avoid dynamic_cast

I need some ideas on how to optimize some code that works more or less as follows:我需要一些关于如何优化一些或多或少工作的代码的想法,如下所示:

struct Notifier
{
  void compute
  {
    for(auto& n : nodes_)
    {
      n->compute(inputs_);
    }
  }

  void add_input(input* i)
  {
    inputs_.push_back(i);
  }
  vector<input*> inputs_;
  vector<node*>  nodes_;
};

struct Node
{
  virtual void compute(vector<input*>& inputs) = 0;
};

struct GraphUpdate
{
  virtual ~GraphUpdate = {}
};

struct DerivedGraphUpdate : public GraphUpdate
{
  //specific business logic
};

struct DerivedGraphUpdate2 : public GraphUpdate
{
  //specific business logic
};

struct DerivedNode : public Node
{
  void compute(vector<input*>& inputs_) override
  {
    for(auto i : inputs_)
    {
        auto update = std::dynamic_pointer_cast<DerivedGraphUpdate>(i->getLastUpdate());
        if(update){
          //process
        }
        auto update = std::dynamic_pointer_cast<DerivedGraphUpdate2>(i->getLastUpdate());
        if(update){
          //process
        }
        //...
    }
  }
};

As you can see GraphUpdate is there just to do some basic type erasure, and everything is processed through dynamic_pointer_casts .如您所见, GraphUpdate只是为了进行一些基本的类型擦除,并且所有内容都通过dynamic_pointer_casts处理。 I am trying to get my head around this problem and try to change it.我试图解决这个问题并尝试改变它。 Ideally I would like the Notifier to notify on the derived classes, such that instead of having a gigantic compute method that has to switch on the types using the pretty horrible dynamic_pointer_cast , it could just have some methods as follows:理想情况下,我希望Notifier通知派生类,这样就不必拥有一个必须使用非常可怕的dynamic_pointer_cast来打开类型的巨大compute方法,它可能只有一些方法,如下所示:

void handle(DerivedGraphUpdate* d);
void handle(DerivedGraphUpdate2* d);

I don't mind that much the big compute method, but I'd like to have a way to get rid of the dynamic_pointer_cast .我不太介意大compute方法,但我想有办法摆脱dynamic_pointer_cast

To be noted, the Notifier doesn't have any knowledge of the actual derived Input and GraphUpdate types, because it was coded to be generic and it's actually on a separate codebase.需要注意的是, Notifier对实际派生的InputGraphUpdate类型没有任何了解,因为它被编码为通用的并且它实际上位于单独的代码库中。

Any ideas?有任何想法吗?

Changing design to avoid dynamic_cast更改设计以避免 dynamic_cast

Use a virtual function:使用虚拟 function:

struct GraphUpdate
{
    virtual void process() = 0;

 virtual ~GraphUpdate = {}

Use = default;使用= default; instead.反而。

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

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