Currently I am working on a C++ project in which I plan to embed Lua scripts. For that reason certain classes need to be exported to Lua and I wanted to make this more convenient therefore I created a template class:
template <class T>
class ExportToLua {
public:
ExportToLua() {}
~ExportToLua() {}
private:
static int m_registered;
};
template <class T> int ExportToLua<T>::m_registered = T::exportToLua();
Now every class that needs to be exported is derived from ExportToLua<T>
with T
="the class to be exported". Example:
class Example: public ExportToLua<Example> {
public:
Example();
virtual ~Example();
static int exportToLua();
private:
};
where Example
's static member function exportToLua()
holds the class-specific registration code. My understanding is that an instance of the static member variable ExportToLua<T>::m_registered
exists for every compile unit - that is - for every T
.
But when I start my program the registration code never gets called. For example in example.cpp:
int Example::exportToLua() {
std::cout << "int Example::exportToLua()" << std::endl;
return -2;
}
however I never see this message when I run my program.
Any idea why? Is the compiler some "optimizing away" the static variable m_registered
, because I am not using it anywhere?
Thanks for your input,
Best, Christoph