/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see .
*/
#pragma once
class no_such_class : public std::runtime_error {
public:
using runtime_error::runtime_error;
};
// BaseType is a base type of a type hierarchy that this registry will hold
// Args... are parameters for object's constructor
template
class class_registry {
using creator_type = std::function(Args...)>;
public:
static void register_class(sstring name, creator_type creator);
template
static void register_class(sstring name);
static std::unique_ptr create(const sstring& name, Args&&...);
static std::unordered_map& classes() {
static std::unordered_map _classes;
return _classes;
}
};
template
void class_registry::register_class(sstring name, class_registry::creator_type creator) {
classes().emplace(name, std::move(creator));
}
template
template
void class_registry::register_class(sstring name) {
register_class(name, [](Args&&... args) {
return std::make_unique(std::forward(args)...);
});
}
template
struct class_registrator {
class_registrator(const sstring& name) {
class_registry::template register_class(name);
}
class_registrator(const sstring& name, std::function(Args...)> creator) {
class_registry::register_class(name, creator);
}
};
template
std::unique_ptr class_registry::create(const sstring& name, Args&&... args) {
auto it = classes().find(name);
if (it == classes().end()) {
throw no_such_class(sstring("unable to find class '") + name + sstring("'"));
}
return it->second(std::forward(args)...);
}
template
std::unique_ptr create_object(const sstring& name, Args&&... args) {
return class_registry::create(name, std::forward(args)...);
}