samedi 27 décembre 2014

Using static initialization to register classes

So I read this article about using static initialization to register classes (http://quantumgraphics.blogspot.nl/2014/11/abusing-static-initialization.html). It's exactly what I need so I decided to implement it. I couldn't get it to work however, so I made a little test case to make sure I got the details right. Turns out even a simple example doesn't work (http://ideone.com/HDr8ZM):



#include <iostream>

int a = 0;

template<
class T
>
class Scriptable {
protected:
struct Proxy
{
Proxy() {
std::cout << "Proxy was executed! ID: " << T::id << std::endl;
a++;
}
};
static Proxy proxy_;
} ;

template<
class T
>
typename Scriptable<T>::Proxy Scriptable<T>::proxy_;

class Object : public Scriptable<Object> {
public:
constexpr static auto id = "[Object]";
} ;

int main() {
std::cout << "Done " << a << std::endl;
}


So basically what needs to happen (or more precisely, what I want to happen) is that the Proxy constructor should be executed before main. I want to use the the Proxy constructor to register the class with some singleton base class factory, but I don't think that's related to this code not working.


Can someone point me in the right direction? I'm probably missing a compiler flag or something (the example should compile with just the -std=c++11 flag). Or is there maybe a better way to do what I'm trying here?


Any help is greatly appreciated!


Aucun commentaire:

Enregistrer un commentaire