c ++ 11带有抽象工厂的派生类的单例

时间:2017-05-22 15:43:15

标签: c++ c++11 inheritance singleton objectfactory

MWE很长,所以请耐心等待。 简而言之,我想使用抽象对象工厂来创建从基类派生的对象,派生对象是单例并使用shared_ptr传递。 到目前为止,如果单身人士不是从单身人士模板中获得任何东西,那么一切正常。

让我们假设一个具有以下结构:

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

我想使用我的抽象对象工厂来生成Derived类,但确保它只创建一次,然后将std :: shared_ptr返回到派生对象。

我已经实现了一个单例模板和一个对象工厂,如果我想创建不是从任何东西派生的对象,那么该工具很有效:

单身人士:

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;

对象工厂:

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...>));
    }
};

让我说我现在想用它:

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

}

我收到很多编辑错误,抱怨移动,我自从过去几个小时以来就无法解决。

你可以帮助我,或者把我改到某个地方。我想要至少甚至可能吗?谢谢!

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 个答案:

答案 0 :(得分:1)

我认为问题在于,foofoo1 = Foo_Factory::Type("foofoo")尝试将std::shared_ptr<Abstract_Factory_Base<Foo,int,int>>类型的对象分配给std::shared_ptr<FooFoo>。这些类型之间没有转换。

要解决此问题,您需要使用返回的工厂对象来创建要存储的对象:

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

FooFoo构造函数的适当参数传递给create

答案 1 :(得分:1)

好吧,我终于为那些对这种设计感兴趣的人设法了。我发现使用原始指针而不是智能指针,我得到一个简单的错误消息:“无法从Foo *转换为FooFoo *。

因此,错误主要在于:

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