簡體   English   中英

跟蹤每個創建的基於模板的單例

[英]Keep track of each created template based singelton

對於我的項目,我需要創建通用類型的單例。 這些單例管理帶有 ID 到對象的std::map 中的泛型類型。 這是我使用的代碼:

template <typename tComponent>
class InternalComponent {
public:
static InternalComponent& getInstance() {
    static InternalComponent s_result;
    return s_result;
}

void add(const tComponent& component, int id) {
    m_components[id] = component;
}

void remove(int id) {
    std::lock_guard<std::mutex> lock(m_mutex);

    auto it = m_components.find(id);
    if (it == m_components.end()) {
        throw std::runtime_error("Component can't be found.");
    }

    m_components.erase(it, m_components.end());
}

void replace(const tComponent& component, int id) {
    auto it = m_components.find(id);
    if (it == m_components.end()) {
        throw std::runtime_error("Component can't be found.");
    }

    m_components[id] = component;
}

tComponent* get(int id) {
    return &m_components[id];
}

private:
    InternalComponent() {};
    InternalComponent(const InternalComponent&);
    InternalComponent & operator = (const InternalComponent &);

    std::mutex m_mutex;
    std::map<int, tComponent> m_components;
};

為了從每個單例中刪除具有特定 ID 的所有組件,我必須跟蹤每個創建的單例實例。 在這一點上,我被困住了。

第一個問題是無法保存到vector的泛型類型。 我會用一個基類繞過它並從中派生 InternalComponent 。

但是我仍然無法保存對向量的引用。

此外,我不確定如何檢查單例是否是第一次創建,而不在每個 getInstance 調用中使用 if 語句,以避免在我創建的單例列表中出現重復條目​​。

我的最后一個問題是:如何在單個列表中管理每個創建的 InternalComponent 實例。

我想出了如何跟蹤我創建的所有基於模板的單身人士。

#include <iostream>
#include <vector>

class Base {
public:
    virtual void delete(int id) = 0;
};

std::vector<Base*> test;

template<typename T>
class S : public Base
{
public:
    void delete(int id) override {
        //delete the component
    };

    static S& getInstance()
    {
        static S    instance;
        return instance;
    }

private:
    S() {
        test.push_back(this);
    }; 
public:
    S(S const&) = delete;
    void operator=(S const&) = delete;
};


int main()
{
    S<int>::getInstance();
    S<char>::getInstance();
    S<char>::getInstance();

    for (auto s : test) {
        s->delete(666);
    }

    exit(0);
}

我使用抽象類稍后在向量中存儲基於模板的類。 該類提供了以后需要的功能。 構造函數只被調用一次,這允許我存儲 this 指針並避免不必要的檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM