gekomad
gekomad

Reputation: 565

C++ Factory of templated sigleton

Here a simple project in C++ with 2 design pattern: singleton and factory, sigleton is a templated class too and an interface (IHash) and a class (Hash1). A simple factory class (HashFactory) creates a sigleton (Hash1); Hash1 inherits the interface IHash and ideally i've Hash1, Hash2 .. HashN.

In compile time i've an error, what's the problem?

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();
                                              ^

Cut and paste this code to compile it:

#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;
}

Upvotes: 0

Views: 132

Answers (1)

Anton Savin
Anton Savin

Reputation: 41321

Hash1's inheritance from Singleton<Hash1> is implicitly private. Change that to

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

Upvotes: 3

Related Questions