每个 class child 实现静态变量的最佳方法是什么? [C++]

What is the best way to implement static variables per class child? [C++]

在我的代码中,我希望 class Component 的所有 children 都有一个唯一的 ID,只在它们自己的实例中共享。现在,我正在实现这样一个系统:

template <class componentType>
struct Component {
    static unsigned int ID;
};

示例组件:

struct Transform: public Component<Transform> {

    float x, y, z;
};

ID 是使用另一种方法分配的。问题是我想要一个组件向量作为另一个 Entity class 的成员变量。另外,我想说 class 具有函数 AddComponent()GetComponent()。现在,这样的实现要求我制作两个函数模板——这会产生各种问题,既必须显式实例化函数的每个版本,又会在这些函数中访问的唯一成员变量是时生成大量不必要的代码ID,我知道它在所有 Component 模板中都很常见。

我可以实现一个被 Component 的每个 child 重写的虚函数,但这需要我为每个 child 复制代码,以及将 ID 系统与不相关的组件 children 结合起来,这似乎是一种不好的做法。为 children 分配唯一 ID 的最佳方法是什么?如果它与模板一起使用,那么如何绕过使用 class?

的方法的问题

你可以做的是让 Component 继承自 Component_base 并且这个 class 有一个由 Component 实现的虚函数 get_id :

#include <iostream>

namespace {
    static unsigned int next_id = 0;

    template<typename T>
    unsigned int get_type_id() {
        static unsigned int id = ++next_id;
        return id;
    }
}

struct Component_base {
    virtual unsigned int get_id() = 0;
};

template <class componentType>
struct Component : public Component_base {

    virtual unsigned int get_id() {
        return Component::ID;
    }

    static unsigned int ID;
};

template <class componentType>
unsigned int Component<componentType>::ID = get_type_id<componentType>();

struct Transform: public Component<Transform> {

    float x, y, z;
};

struct Transform2: public Component<Transform2> {

    float x, y, z;
};

int main() {
    Transform t1;
    Transform2 t2;
    std::cout << t1.get_id() << std::endl;
    std::cout << t2.get_id() << std::endl;
    return 0;
}