c++11 singleton of a derived class with an abstract factory

736 views Asked by At

The MWE is quite long, so please bear with me. To be brief, I would like to use an abstract object factory to create objects derived from a base class, with derived objects made singletons and passed around using shared_ptr. So far, everything works ok if the singletons are not derived from anything except from the singleton template.

Let's assume one has the following structure:

class Base{}
class Derived1 : public Base {} // public Base, public Singleton<Derived1>
class Derived2 : public Base {}

I would like to use my abstract object factory to generate Derived classes, but ensure that it is created only once, and else return a std::shared_ptr to the derived object.

I have implemented a singleton template and an object factory that works well if i want to create objects that are not derived from anything:

The singleton:

template<class Derived>
class Singleton{
    private:
    static std::shared_ptr<Derived> instance_;
    public:
    template <typename... Args>
        static
        std::shared_ptr<Derived> Instance(Args... args){
        if (instance_ == nullptr){
            instance_ = std::shared_ptr<Derived>(
                new Derived(std::forward<Args>(args)...) );
        }
        return instance_;
        }
};
template <class T> std::shared_ptr<T>  Singleton<T>::instance_ = nullptr;

The object factories:

template <class Object, typename... Args>
class Abstract_Factory_Base {
  protected:
    using Factories_Map = std::unordered_map<std::string, std::shared_ptr<Abstract_Factory_Base<Object, Args... >> >;
    static Factories_Map* factories_; ///< \brief stores factories able to construct objects derived from "Object" template parameter

  public:
    Factories_Map* factories(){
        if(factories_ == nullptr){
            factories_ = new Factories_Map;
        }
        return factories_;
    }

    static
    std::shared_ptr<Abstract_Factory_Base<Object, Args...>>
    Type(const std::string &key){
        return (*factories_)[key];
    };

    virtual
    std::shared_ptr<Object>
    create(const Args &... args) = 0;

};


template <class Object, class Derived, typename... Args>
class Abstract_Factory : public Abstract_Factory_Base<Object, Args...>{
  public:
    std::shared_ptr<Object>
        create(const Args &... args){
        return std::shared_ptr<Derived>(
                new Derived(args...));
    }
};
template <class Object, class Derived, typename... Args>
class Factory_Register : public Abstract_Factory<Object, Derived, Args...>{
  public:
    Factory_Register(const std::string& key){
    //static_assert(!(std::is_base_of<Singleton<Derived>, Derived>::value), "");
        this->factories()->emplace(
                key,
                std::shared_ptr<Abstract_Factory_Base<Object, Args...>>(
                        new Abstract_Factory<Object, Derived, Args...>));
    }
};

template <class Object, class Derived, typename... Args>
class Singleton_Factory : public Abstract_Factory_Base<Object, Args...>{
  public:
    std::shared_ptr<Object> create(const Args &... args){
        return Derived::Instance(args...);
    }
};
template <class Object, class Derived, typename... Args>
class Singleton_Factory_Register : public Singleton_Factory<Object, Derived, Args...>{
  public:
    Singleton_Factory_Register(const std::string& key){
        //static_assert(std::is_base_of<Singleton<Derived>, Derived>::value, "");
        this->factories()->emplace(
                key,
                std::shared_ptr<Abstract_Factory_Base<Object, Args...>>(
                        new Singleton_Factory<Object, Derived, Args...>));
    }
};

Lets say i now want to use it with:

class Foo{
    protected:
    int x_, y_;
    public:
    Foo(){x_ = 0; y_ = 0;}
    Foo(int x, int y){
        x_=x;
        y_=y;
    }
    void print(){
    std::cout << x_+y_ << std::endl;
    }
};
using Foo_Factory = Abstract_Factory_Base<Foo,int,int>;

class FooFoo : public Singleton<FooFoo>, public Foo{
    friend class Singleton<FooFoo>;
    using FooFoo_Register = Singleton_Factory_Register<
    Foo,
    FooFoo,
    int,
    int>;
    static FooFoo_Register reg;
    protected:
    //int x_,y_;
    FooFoo(){};
    FooFoo(int x, int y){
        x_=2*x;
        y_=2*y;
    }
    public:
    void print(){
    std::cout << x_ << std::endl;
    }
};

template <class Object, typename... Args>
typename Abstract_Factory_Base<Object, Args...>::Factories_Map* Abstract_Factory_Base<Object, Args...>::factories_;

FooFoo::FooFoo_Register FooFoo::reg("foofoo");


int main(){

    std::shared_ptr<FooFoo> foofoo1, foofoo2, foofoo3;
    foofoo1 = Foo_Factory::Type("foofoo")->create(1,2); // this fails
    Foo_Factory::Type("foofoo"); // this calls ok
    ////foofoo2 = Foo_Factory::Type("foofoo")->create(10,10);
    ////foofoo3 = Foo_Factory::Type("foofoo")->create(2,10);
    ////printf("(%p, %p, %p)\n", foofoo1.get(), foofoo2.get(), foofoo3.get());
    //printf("(%p)\n", foofoo1.get());
    //foofoo1->print();
    ////foofoo2->print();
    ////foofoo3->print();

}

I get plenty of compilations errors, complaning about move, that i'm not able to solve since the past hours.

Can you please help me, or redirect me somewhere. Is want i want at least even possible? Thanks!

In file included from /usr/include/c++/5/bits/shared_ptr.h:52:0,
                 from /usr/include/c++/5/memory:82,
                 from main.cpp:2:
/usr/include/c++/5/bits/shared_ptr_base.h: In instantiation of ‘std::__shared_ptr<_Tp, _Lp>& std::__shared_ptr<_Tp, _Lp>::operator=(std::__shared_ptr<_Tp1, _Lp>&&) [with _Tp1 = Abstract_Factory_Base<Foo, int, int>; _Tp = FooFoo; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’:
/usr/include/c++/5/bits/shared_ptr.h:302:4:   required from ‘std::shared_ptr<_Tp>& std::shared_ptr<_Tp>::operator=(std::shared_ptr<_Tp1>&&) [with _Tp1 = Abstract_Factory_Base<Foo, int, int>; _Tp = FooFoo]’
main.cpp:180:13:   required from here
/usr/include/c++/5/bits/shared_ptr_base.h:1008:4: error: no matching function for call to ‘std::__shared_ptr<FooFoo, (__gnu_cxx::_Lock_policy)2u>::__shared_ptr(std::remove_reference<std::__shared_ptr<Abstract_Factory_Base<Foo, int, int>, (__gnu_cxx::_Lock_policy)2u>&>::type)’
    __shared_ptr(std::move(__r)).swap(*this);
    ^
/usr/include/c++/5/bits/shared_ptr_base.h:1146:7: note: candidate: std::__shared_ptr<_Tp, _Lp>::__shared_ptr(const std::__weak_ptr<_Tp, _Lp>&, std::nothrow_t) [with _Tp = FooFoo; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]
       __shared_ptr(const __weak_ptr<_Tp, _Lp>& __r, std::nothrow_t)
       ^
/usr/include/c++/5/bits/shared_ptr_base.h:1146:7: note:   candidate expects 2 arguments, 1 provided
/usr/include/c++/5/bits/shared_ptr_base.h:1094:2: note: candidate: template<class _Alloc, class ... _Args> std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_make_shared_tag, const _Alloc&, _Args&& ...)
  __shared_ptr(_Sp_make_shared_tag __tag, const _Alloc& __a,
  ^
/usr/include/c++/5/bits/shared_ptr_base.h:1094:2: note:   template argument deduction/substitution failed:
/usr/include/c++/5/bits/shared_ptr_base.h:1008:4: note:   cannot convert ‘std::move<std::__shared_ptr<Abstract_Factory_Base<Foo, int, int>, (__gnu_cxx::_Lock_policy)2u>&>((* & __r))’ (type ‘std::remove_reference<std::__shared_ptr<Abstract_Factory_Base<Foo, int, int>, (__gnu_cxx::_Lock_policy)2u>&>::type {aka std::__shared_ptr<Abstract_Factory_Base<Foo, int, int>, (__gnu_cxx::_Lock_policy)2u>}’) to type ‘std::_Sp_make_shared_tag’
    __shared_ptr(std::move(__r)).swap(*this);
2

There are 2 answers

1
1201ProgramAlarm On

I think the problem is that with foofoo1 = Foo_Factory::Type("foofoo") you try to assign an object of type std::shared_ptr<Abstract_Factory_Base<Foo,int,int>> to one that is a std::shared_ptr<FooFoo>. There is no conversion between these types.

To fix this, you need to use the returned factory object to create the object you want to store:

foofoo1 = Foo_Factory::Type("foofoo")->create(...);

with appropriate parameters for the FooFoo constructor being passed to create.

0
Napseis On

ok, I finally managed for those who are interested in such design. I found out the using raw pointers instead of smart ones, and i got a simple error message: "cannot convert from Foo* to FooFoo*.

Hence, the error is in the main:

std::shared_ptr<Foo> foofoo1, foofoo2, foofoo3;
// Pointer on base class Foo of course !