c++ - 所有带有 "recursion"的 child 的静态变量

标签 c++ inheritance recursion static crtp

我有类似的东西

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/

相关文章:

c++ - 是否可以将 gsl_matrix 存储在 C++ vector 中?

java - Java 中继承的坏例子是什么?

java - 类描述中要写什么

recursion - 迭代过程与递归过程

C# 如何制作 GetEnumerator() 的递归版本

c++ - 在 CppUnit 下运行的测试产生的段错误

c++ - 使用 Windows Imaging Component 将 EMF 转换为 BMP(元文件到位图)

iphone - unique_ptr与Iphone sdk?

javascript - 如何在 JavaScript 的构造函数中重写继承对象的属性?

java - TopCoder SRM 645 - 一个测试用例中的错误