C ++是否可以构建模板类型列表?

时间:2019-06-25 09:21:02

标签: c++ templates

所以我不知道这是否可行,但是我的设置看起来有点像:

template <class T>
struct Something;

struct Example {
    //not sure how this should be defined
    //I was thinking void*, but I can't use pointers as the 'Something' class moves around the instances
    //and I don't want to have to constantly update the pointers.
    std::vector<?> addedTypes;

    template<typename T>
    void addThing() {
        addedTypes.push_back(T);
        Something<T>::addThing(*this);
    }

    void destroy() {
        for (auto T : addedTypes) {
            Something<T>::removeThing(*this);
        }
    }
};

template <class T>
struct Something {
    static void addThing(Example e) {/*...*/}
    static void removeThing(Example e) {/*...*/}
};

基本上我想知道如何制作已添加到循环中的类型的列表,以便以后可以调用静态删除功能?

编辑:根据评论的建议添加更多信息。

例如,这实际上是一个实体组件系统,其中“ Example”是实体,而“ Something”是CRTP组件。除了实体中的ID和一些辅助功能外,所有逻辑都存储在组件中。唯一缺少的部分是从实体中销毁各种类型的组件的方法(我已经可以从组件中做到这一点,但是没有类型,我不确定如何从实体中解决这个问题。 / p>

由于静态函数在“其他”类中被调用的原因,它们与其他静态类成员(例如std::vector<T> list)进行交互,并且不涉及实例化成员状态。

1 个答案:

答案 0 :(得分:6)

它不是建筑类型列表,而是提供“删除”列表。

我在这里使用std::function,也许创建IRemover对您来说更有意义(或者简单的函数指针就足够了):

template <class T>
struct Something;

struct Example {
    std::vector<std::function<void(Example&)>> removers;

    template<typename T>
    void addThing() {
        removers.push_back(&Something<T>::removeThing);
        Something<T>::addThing(*this);
    }

    void destroy() {
        for (auto& f : removers) {
            f(*this);
        }
        removers.clear();
    }
};
相关问题