具有抽象工厂的派生类的 C++11 单例

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

MWE很长,还请大家多多包涵。 简而言之,我想使用一个抽象对象工厂来创建从基类派生的对象,派生对象成为单例并使用 shared_ptr 传递。 到目前为止,如果单例不是从单例模板派生的,则一切正常。

假设一个具有以下结构:

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

我想使用我的抽象对象工厂来生成派生类,但要确保它只创建一次,否则将 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);

最佳答案

我认为问题在于 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 .

关于具有抽象工厂的派生类的 C++11 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117029/

相关文章:

c++ - 不正确的 OpenGL 缠绕

c++ - 我们如何使用引用类型实例化模板函数?

python - 防止初始化扩展单例类的类

c++ - 带有继承的 Pimpl 成语

C++ 类继承顺序

c++ - 如何纠正段错误?

c++ - C++ 中的迭代器开始/结束与 :collection

c++ - 调用基类克隆实现

c++ - void 作为文字类型?

C++ : Throw Exception weird behavior?