ppforest2 v0.1.0
Projection Pursuit Decision Trees and Random Forests
Loading...
Searching...
No Matches
Strategy.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <map>
4#include <memory>
5#include <stdexcept>
6#include <string>
7
8#include <nlohmann/json.hpp>
9
23template<typename Derived> struct Strategy {
24 using Ptr = std::shared_ptr<Derived>;
25
27 using Factory = Ptr (*)(nlohmann::json const&);
28
29 virtual ~Strategy() = default;
30
39 virtual void to_json(nlohmann::json& j) const = 0;
40
42 virtual std::string display_name() const = 0;
43
55 static bool register_strategy(std::string const& name, Factory factory) {
56 registry()[name] = factory;
57 return true;
58 }
59
68 static Ptr from_json(nlohmann::json const& j) {
69 auto name = j.at("name").get<std::string>();
70 auto& reg = registry();
71 auto it = reg.find(name);
72
73 if (it == reg.end())
74 throw std::runtime_error("Unknown strategy: " + name);
75
76 return it->second(j);
77 }
78
79private:
80 static std::map<std::string, Factory>& registry() {
81 static std::map<std::string, Factory> r;
82 return r;
83 }
84};
85
100#define PPFOREST2_REGISTER_STRATEGY(StrategyBase, name) \
101 inline static const bool registered_ = StrategyBase::register_strategy(name, from_json);
CRTP base class providing self-registration for strategy types.
Definition Strategy.hpp:23
Ptr(*)(nlohmann::json const &) Factory
Factory function type for deserializing a strategy from JSON.
Definition Strategy.hpp:27
std::shared_ptr< Derived > Ptr
Definition Strategy.hpp:24
virtual void to_json(nlohmann::json &j) const =0
Serialize this strategy's configuration to JSON.
static Ptr from_json(nlohmann::json const &j)
Construct a strategy from its JSON representation.
Definition Strategy.hpp:68
static bool register_strategy(std::string const &name, Factory factory)
Register a concrete strategy for JSON deserialization.
Definition Strategy.hpp:55
virtual ~Strategy()=default
virtual std::string display_name() const =0
Human-readable name for display in summaries.