-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPluginFactory.hpp
More file actions
69 lines (57 loc) · 1.95 KB
/
Copy pathPluginFactory.hpp
File metadata and controls
69 lines (57 loc) · 1.95 KB
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
// Noise Plethora
// Copyright (c) 2021 Befaco / Jeremy Bernstein
// Open-source software
// Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
// See LICENSE.txt for the complete license text
#pragma once
#include <memory>
#include <string> // string might not be allowed
#include <functional>
#include <map>
// necessary (because we're using <string>?)
extern "C" {
__attribute__((weak))
int __exidx_start(){ return -1;}
__attribute__((weak))
int __exidx_end(){ return -1; }
}
class Plugin;
// stolen from/inspired by
// https://www.codeproject.com/Articles/567242/AplusC-2b-2bplusObjectplusFactory
class PluginFactory {
public:
static PluginFactory* Instance() {
static PluginFactory factory;
return &factory;
}
std::unique_ptr<Plugin>
Create(std::string name) {
std::unique_ptr<Plugin> instance;
if (name.empty()) {
Serial.println("Cannot instantiate a NullPlugin.");
return instance;
// name = "TestPlugin";
}
// find name in the registry and call factory method.
auto it = factoryFunctionRegistry.find(name);
if (it != factoryFunctionRegistry.end()) {
instance = it->second();
}
// wrap instance in a shared ptr and return
return instance;
}
void RegisterFactoryFunction(std::string name,
std::function<std::unique_ptr<Plugin>(void)> classFactoryFunction) {
// register the class factory function
factoryFunctionRegistry[name] = classFactoryFunction;
}
std::map<std::string, std::function<std::unique_ptr<Plugin>(void)>> factoryFunctionRegistry;
};
template<class T> class Registrar {
public:
Registrar(std::string className) {
// register the class factory function
PluginFactory::Instance()->RegisterFactoryFunction(className,
[](void) -> std::unique_ptr<Plugin> { return std::make_unique<T>(); });
}
};