• c++工厂注册类


    工厂注册类

    利用模版形式注册类

    #include 
    #include 
    #include 
    namespace cyn {
    
    
    //自定义断言
    //#ifndef _DEBUG // _RELEASE  或者 _DEBUG  ,根据你的编译器/构建系统
    #ifdef _DEBUG // _RELEASE  或者 _DEBUG  ,根据你的编译器/构建系统
    #define CHECK(cond) \
        do { \
        if (!(cond)) { \
        std::cerr << "Assertion failed: (" << #cond << "), function " << __FUNCTION__ \
        << ", file " << __FILE__ << ", line " << __LINE__ << "." << std::endl; \
    } \
    } while (0)
    #define CHECK_EX(cond, msg) \
        do { \
        if (!(cond)) { \
        std::cerr << "Assertion failed: (" << #cond << "), function " << __FUNCTION__ \
        << ", file " << __FILE__ << ", line " << __LINE__ << "." << std::endl; \
        std::cerr << "Message: " << msg << std::endl; \
        throw std::runtime_error(msg); \
    } \
    } while (0)
    #else
    #define CHECK(cond) \
        do { \
        \
    } while (0)
    #define CHECK_EX(cond, msg) \
        do { \
        \
    } while (0)
    #endif
    
    
    
    // 参数基类
    class LayerParams
    {
    public:
        virtual ~LayerParams() = default;
    };
    // 具体参数类型
    class DenseLayerParams : public LayerParams {
    public:
        int units;
        float learning_rate;
    
        DenseLayerParams(int units, float learning_rate) : units(units), learning_rate(learning_rate) {}
    };
    
    // 基类
    class Layer
    {
    public:
        Layer(const std::string& name,const std::shared_ptr<LayerParams>& params) : name(name),layer_params(params){}
    
        virtual int forward(int){return 0;};
    
    
    public:
        int input_;
        std::string name;
        std::shared_ptr<LayerParams> layer_params;
    };
    
    //获取类型名字
    template <typename T>
    constexpr auto class_type_name() noexcept
    {
        std::string_view name, prefix, suffix;
    #ifdef _MSC_VER
        name = __FUNCSIG__;
        prefix = "auto __cdecl cyn::class_type_name;
        suffix = ">(void) noexcept";
    #elif defined(__GNUC__)
        name = __PRETTY_FUNCTION__;
        prefix = "constexpr auto cyn::class_type_name() [with T = cyn::";
        suffix = "]";
    #elif defined(__clang__)
        name = __PRETTY_FUNCTION__;
        prefix = "constexpr auto cyn::class_type_name() [with T = cyn::";
        suffix = "]";
    
    #endif
        name.remove_prefix(prefix.size());
        name.remove_suffix(suffix.size());
        return name;
    }
    
    // 定义一个注册表基类模版
    template <typename T, typename... Args>
    class Factory
    {
        using CreateFunction = std::function<std::shared_ptr<T>(Args...)>;
        Factory(){}
    
    public:
        virtual ~Factory() = default;
    
        static Factory& Instance()
        {
            static Factory instance;
            return instance;
        }
        void Register(const std::string & name,const CreateFunction& create)
        {
            std::cout <<"Factory Register name:"<< std::string(name) << std::endl;
            registry[std::string(name)] = create;
        }
    
        std::shared_ptr<T> Create(const std::string& name,Args... args)
        {
    
            if (registry.find(name) != registry.end())
            {
                std::cout <<"Create succeed:"<< std::string(name) << std::endl;
                return registry[name](args...);
            }
            std::cout <<"Create fail:"<< std::string(name) << std::endl;
            return nullptr;
        }
    private:
        std::unordered_map<std::string, CreateFunction> registry;
    };
    //注册类 统一接口
    template <typename Base, typename Impl, typename... Args>
    class Register
    {
    public:
        explicit Register()
        {
            std::cout<<"Register name:  "<<std::string(class_type_name<Impl>())<<std::endl;
            //流程6
            Factory<Base, Args...>::Instance().Register(std::string(class_type_name<Impl>()), [](Args... args)
            {
                return std::shared_ptr<Base>(new Impl(args...));
            });
        }
    };
    
    
    
    
    
    
    
    
    
    
    
    // LayerSub  在这很关键,实现了继承LayerSub  (也就是继承基类)自动注册
    //注册Layer子类,实现继承自动注册  T 为Layer子类类型
    /*
     * 继承LayerSub-构造函数->(void)registered->trigger()->_register(str)
     */
    template <typename T>
    class LayerSub : public Layer
    {
        //流程4
        static bool trigger()
        {
            //流程5
            Register<Layer,T,std::shared_ptr<LayerParams>> _register;
            return true;
        }
    protected:
        //流程2
        LayerSub(const std::shared_ptr<LayerParams>& params) : Layer(std::string(class_type_name<T>()),params)
        {
            std::cout<<"LayerSub:"<<std::string(class_type_name<T>())<<std::endl;
    
            //流程3
            (void)registered;
        }
    
    public:
        static bool registered;
    
    };
    template <typename T>
    bool LayerSub<T>::registered = LayerSub<T>::trigger();
    
    //定义Layer类 创建接口
    typedef Factory<Layer, std::shared_ptr<LayerParams>> LayerFactory;
    
    
    
    // 具体层类型
    
    class DenseLayer : public LayerSub<DenseLayer>
    {
    public:
        DenseLayer(const std::shared_ptr<LayerParams>& params) : LayerSub(params)
        {
            std::cout<<"DenseLayer constructor!"<<std::endl;
            std::shared_ptr<DenseLayerParams> p = std::dynamic_pointer_cast<DenseLayerParams>(params);
    
            //检查参数类型 - 调试用
            CHECK_EX(p,"error");
    
    
            //打印参数值
            std::cout<<p->units<<std::endl;
            std::cout<<p->learning_rate<<std::endl;
        }
        int forward(int s) override  {
    
            std::cout<<"wo shi zi lei!"<<s<<std::endl;
            return s;
        }
    };
    
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        std::shared_ptr<cyn::DenseLayerParams> param = std::make_shared<cyn::DenseLayerParams>(100,1);
        auto ss = cyn::LayerFactory::Instance().Create(std::string("DenseLayer"), param);
    
        ss->forward(1);
        return a.exec();
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229

    输出结果
    Register name: DenseLayer
    Factory Register name:DenseLayer
    Create succeed:DenseLayer
    LayerSub:DenseLayer
    DenseLayer constructor!
    100
    1
    wo shi zi lei!1

  • 相关阅读:
    常见的软件脱壳思路
    Redis与分布式:主从复制
    留言板
    springboot引入redisson分布式锁及原理
    JS事件监听器
    小白也能看懂的 ROC 曲线详解
    全文解读 | 五部委印发:元宇宙产业创新发展三年行动计划(2023-2025年)
    Prometheus指标
    神经网络与深度学习第四章前馈神经网络习题解答
    springboot配置全局异常拦截
  • 原文地址:https://blog.csdn.net/weixin_43763292/article/details/133896148