I recently designed a struct like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// MyMap.h
typedef std::map<std::string, std::function<void ()>> MyMap;
extern MyMap g_mymap;
// MyMap.cpp
My Map g_mymap;
// a.cpp
#include "MyMap.h"
class A {
public: A() { g_mymap["a"] = [] () { std::cout << "function a"; }; }
}
static A a;
// b.cpp
#include "MyMap.h"
class B {
public: B() { g_mymap["b"] = [] () { std::cout << "function b"; }; }
}
static B b;
|
It looks useful to implement strategy pattern because it makes a fully separate code block.
So I can add a function to the map simply by compiling a source file.
It's very simple. I don't need to edit another file.
But when I use it for my existing project, It makes some linking and runtime errors.(vs 2012)
I can't recognize exactly why because it is a huge project.
Anyway, I have a question that - Is this a safe use of class constructor?
I know that there is no fixed order of running, but in this case I think it doesn't matter. because they are independent.
But it is not a common pattern, so I can't decide to use it.
Dose someone have experience or opinion about it?