Skip to content

Instantly share code, notes, and snippets.

@sasq64
Created June 27, 2013 15:22
Show Gist options
  • Select an option

  • Save sasq64/5877376 to your computer and use it in GitHub Desktop.

Select an option

Save sasq64/5877376 to your computer and use it in GitHub Desktop.
#include <string>
#include <unordered_map>
#include <functional>
#include <vector>
#include <assert.h>
#include <stdio.h>
/*
template <typename T> class InjectionPoint {
public:
bool apply(T &arg) {
};
};
*/
class Injection {
};
template <typename T> class TypedInjection : public Injection {
public:
TypedInjection(const std::string &name) {
}
bool apply(T &t) {
for(auto &fn : injectors) {
bool rc = fn(t);
if(!rc)
return false;
}
return true;
}
void addListener(const std::function<bool(T&)> &fn) {
injectors.push_back(fn);
}
std::vector<std::function<bool(T&)>> injectors;
};
/*class InjectionManager {
public:
template <typename T> void addInjectionPoint(const std::string &name) {
injections.push_back(new TypedInjection<T>(name));
}
}; */
std::unordered_map<std::string, Injection*> injections;
//void inject(const std::string &name, std::function<bool(InjectionData&)> fn) {
template <typename T> void inject(const std::string &name, std::function<bool(T&)> fn) {
//InjectionManger *im = InjectionManager.getInstance();
Injection *injection;
if(injections.count(name) == 0) {
injection = new TypedInjection<T>(name);
injections[name] = injection;
} else
injection = injections[name];
//TypedInjection<T> *tInjection = static_cast<TypedInjection<T>*>injection;
TypedInjection<T> *tInjection = (TypedInjection<T>*)injection;
tInjection->addListener(fn);
}
template <typename T> bool injection_point(const std::string &name, T& data) {
Injection *injection = injections[name];
if(injection) {
TypedInjection<T> *tInjection = (TypedInjection<T>*)injection;
return tInjection->apply(data);
}
return false;
}
void inject_test() {
inject<std::string>("test", [](std::string &s) -> bool {
s.append(".x");
return true;
});
}
int main(int argc, char **argv) {
inject_test();
std::string name = "data";
injection_point("test", name);
printf("%s\n", name.c_str());
assert(name == "data.x");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment