模板化单例的 C++ 工厂

标签 c++ templates design-patterns singleton factory-pattern

这是一个简单的 C++ 项目,有 2 种设计模式:单例和工厂,sigleton 也是一个模板化类,一个接口(interface) (IHash) 和一个类 (Hash1)。 一个简单的工厂类 (HashFactory) 创建一个 sigleton (Hash1); Hash1 继承接口(interface) IHash,理想情况下我有 Hash1、Hash2 .. HashN。

编译时出现错误,请问是什么问题?

g++  main.cpp 
main.cpp: In static member function ‘static IHash* HashFactory::get(int)’:
main.cpp:11:15: error: ‘static T& Singleton<T>::getInstance() [with T = Hash1]’ is inaccessible
static T &getInstance() {
           ^
main.cpp:76:50: error: within this context
     if (type == 1)return &Hash1::getInstance();
                                              ^

剪切并粘贴此代码以对其进行编译:

#include <iostream>
using namespace std;
///////////////////////////////////////////////
//Class Singleton
 template<class T>
class Singleton {
public:

static T &getInstance() {
    if (!_instanceSingleton) {
        _instanceSingleton = new T();
    }
    return *_instanceSingleton;
}

private:
    static T *_instanceSingleton;
};

template<class T> T *Singleton<T>::_instanceSingleton = 0;

/////////////////////////////////////////////////
//Interface IHash
class IHash {

public:

    void function1() {
        cout << "function1";
    }

    virtual void recordHash(bool b) = 0;

    ~IHash() {
        dispose();
    }


private:

    void dispose() {
        cout << "dispose\n";
    }
};

///////////////////////////////////////////////////
//Class Hash1 is a singleton and inherits IHash

class Hash1 : public IHash, Singleton<Hash1> {
    friend class Singleton<Hash1>;
public:
    void recordHash(bool b);
private:
    //private constructor, is a sigleton
    Hash1();
};

Hash1::Hash1() {
    cout << "create Hash1\n";
}

void Hash1::recordHash(bool b) {
    cout << b << " recordHash\n";
}


////////////////////////////////////////////////////
//Factory for IHash
class HashFactory {
public:
    static IHash *get(int type) {
        if (type == 1)return &Hash1::getInstance();
//        if (type == 2)return &Hash2::getInstance();
//        if (type == 3)return &Hash3::getInstance();
        return 0;
    }
};

//////////////////////////////////////////////////////

int main() {
    int type=1;
    IHash *a = HashFactory::get(type);
    a->recordHash(true);
    a->function1();
    return 0;
}

最佳答案

Hash1继承自 Singleton<Hash1>是隐式私有(private)的。将其更改为

class Hash1 : public IHash, public Singleton<Hash1> {

关于模板化单例的 C++ 工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207439/

相关文章:

.net - 相互通知模式

C++ 我应该使用什么类型的指针来存储 `algorithm` `remove` 函数的输出地址?

c++ - 如何使用 Qt5 编译 Qt FTP webkit 示例?

java - freemarker 模板中的日期格式问题

c++ - 在 C++ OOP 中,谁负责删除传递给构造函数的对象

java - 多次调用同一方法时取消方法调用

c++ - 从静态构造函数代码调用时 pthread 库失败

c++ - 在 .cpp 标准中包含文件

c++ - 帮助双向链表?

c++ - 在具有不同 CRT 的库中使用 shared_ptr<T>