【问题标题】:avoid member access for shared base state避免共享基本状态的成员访问
【发布时间】:2021-07-28 19:35:41
【问题描述】:

假设我有一个作为抽象接口的基类和两个从基类继承特定状态的派生类。我想更改我在运行时使用的派生类,但我想保留共享状态。

class Base{
public:
virtual void abstract() = 0;
SharedState ss;
};

class Der1 : public Base{
Der1() = default;
virtual void abstract() {//bla bla};
Der1(SharedState &s){
ss = s;};
};

class Der2 : public Base{
Der2() = default;
virtual void abstract(){//bla bla 2};
Der2(SharedState &s){
ss = s;};
};

struct SharedState{
int x,y,z;
float x1,y1,z1; 
//etc...
}

我的处理程序代码,我有一个智能指针,它在运行时根据类类型改变行为,因此是共享状态构造函数。

 //driver code
std::unique_ptr<Base> ptr = std::make_unique<Der1>();

我打算更改类型,但是使用这样的构造函数我可以保留状态。然而,以ss. 开头共享状态的每个成员非常烦人,有没有办法避免这种情况,也许使用某种 using 声明?

编辑:我知道我可以移动基础中的共享状态并将其设为静态,但是当我不使用此接口时会导致性能下降。

【问题讨论】:

  • 您的问题是如何避免每次访问共享状态时都必须输入ss.
  • @JohnFilleau 是的
  • 不要使用struct,直接把共享状态放在Base中,如xyz等。
  • @JohnFilleau 当共享状态增长时,当我在驱动程序代码中更改派生类时如何移动它?我宁愿避免使用 20 个参数的构造函数。
  • 这不是很好,但你可以让SharedState 成为Base 的基类

标签: c++ state abstract-class unique-ptr member-access


【解决方案1】:

这是一个丑陋的答案,但它解决了“ss”问题并且很有用。

我重载了操作符[] 直接返回你的struct 的值

struct SharedState{
int x,y,z;
float x1,y1,z1; 
//etc...
};


class Base{
public:
virtual void abstract() = 0;
SharedState ss;
public:
  int& operator[](const std::string rhs) 
  {                          
    if(rhs == "x") //Here you will manage all the struct members, probably a map
    return this->ss.x; // return the result by reference
  }
};

class Der1 : public Base{
void abstract() override { };
public:
Der1(SharedState &s){
ss = s;};
};

class Der2 : public Base{
void abstract() override { };
public:
Der2(SharedState &s){
ss = s;};
};



int main()
{
  SharedState ss;
  ss.x = 100;
  std::unique_ptr<Base> ptr = std::make_unique<Der1>(ss);
  
  std::cout << (*ptr)["x"] << std::endl;
  (*ptr)["x"] = 5; // You can change it too 
  std::cout << (*ptr)["x"] << std::endl;
  
  std::unique_ptr<Base> ptr2 = std::make_unique<Der2>(ptr->ss);
  std::cout << (*ptr2)["x"] << std::endl;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
相关资源
最近更新 更多