所有"recursion"患儿的静态变量

Static variable in all children with "recursion"

本文关键字:静态 变量 recursion 所有      更新时间:2023-10-16

我有类似

的东西
struct Base{
  int x=0;
};

我希望所有的孩子都有一个静态变量的" myint",以便在建造时,它们会累积所有父母和自己的Myint值。(实际上,在我的情况下,X是一组,我想要的是每个孩子集的结合)。

struct Derived : public Base {
  static int myint =1;
  Derived(){x+=myint;}
};
struct Derived2 : public Derived {
  static int myint = 2;
  Derived2(){x+=myint;}
};

因此,derived2。

我已经看到,使用CRTP(每个派生类的静态变量)编写Basex类是可能的:

template<class A>
struct BaseX : public Base {
  static int myint;
  BaseX() {Base::x+=myint;}
}
struct Derived : public BaseX<Derived>;

但是,这种模式不能用于继承的第二层。我尝试使用多个继承尝试,但是我当然获得的是,我有两个值的值,每个值的值都有错误的值(例如,从派生中继承的零件为x = 1,而从basex派生的零件x = 2)。

您是否看到了此问题的任何解决方案,而无需在所有构造函数中打电话(x = myint)并在每个派生中定义myint?

非int/enum类型的变化:

#include <iostream>
#include <set>
#include <string>
struct Base {
    std::set<std::string> x;
};
template <class BASE>
struct Derived : BASE {
    static const std::string my_str;
    Derived() {
        this->x.insert(my_str);
    }
};
struct Derived1 : Derived<Base> {};
template<>
const std::string Derived<Base>::my_str = "derived";
struct Derived2 : Derived<Derived1> {};
template<>
const std::string Derived<Derived1>::my_str = "derived2";
int main() {
    Derived1 d1;
    Derived2 d2;
    for (const auto & word : d1.x) {
        std::cout << word << std::endl;
    }
    for (const auto & word : d2.x) {
        std::cout << word << std::endl;
    }
}

我会这样做:

#include <iostream>
struct Base {
    int x = 0;
};
template <class BASE, int MY>
struct Derived : BASE {
    static const int myint = MY;
    Derived() {
        this->x += myint;
    }
};
struct Derived1 : Derived<Base, 1> {};
struct Derived2 : Derived<Derived1, 2> {};
int main() {
    Derived1 d1;
    Derived2 d2;
    std::cout << d1.x << std::endl;
    std::cout << d2.x << std::endl;
}

我必须感谢toxa evtushenko的帮助。多亏了他的想法,我想出了这种变体,我相信可以以一种一般的方式应用:

#include <iostream>
#include <set>
#include <string>
struct Base {
  std::set<std::string> x;
};
template<class DERIVED>
struct help{
  static const std::string my_str;
};
template <class BASE, class DERIVED>
struct Derived : BASE {
private:
  help<DERIVED> val;
public:
  Derived() {
    this->x.insert(val.my_str);
  }
};
struct Derived1a;
template<> const std::string help<Derived1a>::my_str = "Derived1A";
struct Derived1a : Derived<Base,Derived1a> {};
struct Derived1b;
template<> const std::string help<Derived1b>::my_str = "Derived1B";
struct Derived1b : Derived<Base,Derived1b> {};
struct Derived2;
template<> const std::string help<Derived2>::my_str = "Derived2";
struct Derived2 : Derived<Derived1a,Derived2> {};
int main() {
  Derived1a d1a;
  Derived1b d1b;
  Derived2  d2;
  for (const auto & word : d1a.x) {
    std::cout << word << std::endl;
  }
  std::cout << std::endl;
  for (const auto & word : d1b.x) {
    std::cout << word << std::endl;
  }
  std::cout << std::endl;
  for (const auto & word : d2.x) {
    std::cout << word << std::endl;
  }
}

当然欢迎更多优雅的解决方案!