我有类似的东西
struct Base{
int x=0;
};
而且我希望所有的 child 都有一个静态变量“myint”,这样在构建时,它们会在 x 中为所有 parent 和他们自己累积 myint 的值。 (实际上在我的例子中 x 是一个集合,我想要的是每个 child 的集合的并集)。
struct Derived : public Base {
static int myint =1;
Derived(){x+=myint;}
};
struct Derived2 : public Derived {
static int myint = 2;
Derived2(){x+=myint;}
};
所以 Derived 的 x=1,Derived2 的 x=3。
我已经看到使用 CRTP ( static variable for each derived class ) 编写 BaseX 类可以实现这样的事情:
template<class A>
struct BaseX : public Base {
static int myint;
BaseX() {Base::x+=myint;}
}
struct Derived : public BaseX<Derived>;
但是这种模式不能应用于二级继承。我尝试了多重继承,但我得到的当然是我有两个 x 值,每个值都有错误的值(对于从 Derived 继承的部分说 x=1,对于从 BaseX 派生的部分说 x=2 ).
您是否看到无需在所有构造函数中调用 (x+=myint) 并在每个派生函数中定义 myint 即可解决此问题的解决方案?
最佳答案
非整数/枚举类型的变体:
#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;
}
}
关于c++ - 所有带有 "recursion"的 child 的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46325095/