本文主要是介绍C++去掉宏的自注册工厂,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现思路
借助CRTP和静态变量的初始化顺序来实现
静态变量的初始化是在main函数之前,利用静态变量的初始化实现自注册
实现代码
#include <memory>
#include <map>
#include <functional>
#include <iostream>struct message_base;template<typename... Args>
class MsgFactory {
public:MsgFactory() = delete;using CreateMethod = std::function<std::unique_ptr<message_base>(std::tuple<Args...>)>;static bool Register(size_t id, CreateMethod creator){auto& map = GetMap();auto it = map.find(id);if (it == map.end()){map[id] = creator;std::cout << id << " registered\n";return true;}return false;}static std::unique_ptr<message_base> Create(size_t id, Args... args){auto& map = GetMap();auto it = map.find(id);if (it != map.end())return it->second(std::make_tuple(args...));return nullptr;}static std::map<size_t, CreateMethod>& GetMap() {static std::map<size_t, CreateMethod> map;return map;}
};template <typename T, typename... Args>
class AutoMsgFactory
{
protected:static bool registered_;
};template<typename T, typename... Args>
std::unique_ptr<T> create(std::tuple<Args...> t) {return std::apply([](Args... args) {return std::make_unique<T>(args...);}, t);
}template <typename T, typename... Args>
bool AutoMsgFactory<T, Args...>::registered_ = MsgFactory<Args...>::Register(T::Id(), [](std::tuple<Args...> args) { return create<T>(args); });struct message_base {virtual ~message_base() {}
};struct message1 : public message_base, AutoMsgFactory<message1>
{static size_t Id() {assert(!registered_);//registered_保证当前类会被自动注册//避免重复注册,重复注册时会触发断言错误//编译期限定派生类必须定义一个Id函数,保证派生类不会忘记定义创建该类需要的唯一id//id是自定义的,可以是枚举类型也可以是整形return 1;}
};struct message2 : public message_base, AutoMsgFactory<message2>
{static size_t Id() {assert(!registered_);return 2;}
};struct message4 : public message_base, AutoMsgFactory<message4, int>
{message4(int) {}static size_t Id() {assert(registered_);return 4;}
};auto msg = MsgFactory<int>::Create(4, 1);
if (msg) {std::cout << typeid(msg).name() << std::endl;
}auto msg1 = MsgFactory::Create(1);
if (msg1) {std::cout << typeid(msg1).name() << std::endl;
}auto msg2 = MsgFactory::Create(2);
if (msg2) {std::cout << typeid(msg2).name() << std::endl;
}
这篇关于C++去掉宏的自注册工厂的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!