meta/runtime/meta_registry.h
2024-03-06 08:55:49 +08:00

71 lines
1.7 KiB
C++

#pragma once
#ifndef META_RUNTIME_META_REGISTRY_H
#define META_RUNTIME_META_REGISTRY_H
#include "meta_object.h"
#include <functional>
#include <unordered_map>
namespace meta {
/**
* Registry
**/
template<typename... Args>
class MetaRegistry {
public:
static MetaRegistry *Instance();
static bool Register(const std::string &obj_name,
std::function<MetaObject *(Args &&...)> creator);
static bool Unregister(const std::string &obj_name);
private:
bool RegisterImpl(const std::string &obj_name, std::function<MetaObject *(Args &&...)> creator);
bool UnregisterImpl(const std::string &obj_name);
std::unordered_map<std::string, std::function<MetaObject *(Args &&...)>> creators_;
};
template<typename... Args>
MetaRegistry<Args...> *
MetaRegistry<Args...>::Instance()
{
static MetaRegistry<Args...> instance;
return &instance;
}
template<typename... Args>
bool
MetaRegistry<Args...>::Register(const std::string &obj_name,
std::function<MetaObject *(Args &&...)> creator)
{
return Instance()->RegisterImpl(obj_name, creator);
}
template<typename... Args>
bool
MetaRegistry<Args...>::Unregister(const std::string &obj_name)
{
return Instance()->UnregisterImpl(obj_name);
}
template<typename... Args>
bool
MetaRegistry<Args...>::RegisterImpl(const std::string &obj_name,
std::function<MetaObject *(Args &&...)> creator)
{
return creators_.insert({obj_name, creator}).second;
}
template<typename... Args>
bool
MetaRegistry<Args...>::UnregisterImpl(const std::string &obj_name)
{
return creators_.erase(obj_name) > 0;
}
}// namespace meta
#endif// META_RUNTIME_META_REGISTRY_H