简体   繁体   English

避免共享基础 state 的成员访问

[英]avoid member access for shared base state

Suppose I have a base class that is an abstract interface, and two derived classes, which inherit a certain state from the base class.假设我有一个作为抽象接口的基础 class 和两个派生类,它们从基础 class 继承某个 state。 I want to change which derived class I'm using at run-time, but I want to preserve the shared state.我想更改我在运行时使用的派生 class,但我想保留共享的 state。

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...
}

I my handler code, I have a smart pointer that changes behaviour based on class type at run-time, hence the shared state constructor.我的处理程序代码,我有一个智能指针,它在运行时根据 class 类型更改行为,因此共享 state 构造函数。

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

I'm planning to change the type, but with such a constructor I can preserve the state.我打算更改类型,但是使用这样的构造函数,我可以保留 state。 However it is highly annoying to preface every member of the shared state with ss.然而,在共享 state 的每个成员前面加上ss. , is there a way to avoid this, perhaps with a using declaration of some sort? ,有没有办法避免这种情况,也许有某种使用声明?

Edit: I know I can move the shared state in the base and make it static, but that leads to performance drops when I'm not using this interface.编辑:我知道我可以将共享的 state 移动到底座中并使其成为 static,但是当我不使用此接口时会导致性能下降。

This is an ugly answer, but is an answer, solves the "ss" problem and can be usefull.这是一个丑陋的答案,但却是一个答案,解决了“ss”问题并且很有用。

I overloaded the operator [] to directly return the values of your struct我重载了运算符[]以直接返回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;
}

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

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