V
V
Vladimir Semenyakin2016-01-27 22:05:08
C++ / C#
Vladimir Semenyakin, 2016-01-27 22:05:08

How to execute actions before main function is called (header-only solution)?

I'm trying to write my own class registration system for C++. This is necessary to automate polymorphic serialization in C ++ (save and load objects through a pointer to the base class).
Registering classes requires certain steps to be taken before the main() function is run. This can be done by calling the global variable constructors. For example, like this:

Current Solution
#define COMBINE1(X,Y,Z) X##Y
#define COMBINE(X,Y,Z) COMBINE1(X,Y,Z)

//-----------------------------------------------------------------------------
#define BEFORE_MAIN_START_DEFFERED_TASK_0_ARG(M_TaskID,\
      M_TaskType, M_Priority)\
class M_TaskID {\
public:\
   M_TaskID() {\
      sBeforeMainStart.addTask(\
         new M_TaskType(), M_Priority);\
   }\
} s##M_TaskID;

//-----------------------------------------------------------------------------
#define BEFORE_MAIN_START_DEFFERED_TASK_1_ARG(M_TaskID,\
         M_TaskType, M_Arg1, M_Priority)\
class M_TaskID {\
public:\
   M_TaskID() {\
      sBeforeMainStart.addTask(\
         new M_TaskType(M_Arg1), M_Priority);\
   }\
} s##M_TaskID;

//-----------------------------------------------------------------------------
#define BEFORE_MAIN_START_DEFFERED_TASK_2_ARG(M_TaskID,\
      M_TaskType, M_Arg1, M_Arg2, M_Priority)\
class M_TaskID {\
public:\
   M_TaskID() {\
      sBeforeMainStart.addTask(\
         new M_TaskType(M_Arg1, M_Arg2), M_Priority);\
   }\
} s##M_TaskID;

//-----------------------------------------------------------------------------
#define PERFORM_BEFORE_MAIN_START_DEFFERED_ACTIONS()\
      sBeforeMainStart.performTaskQueue();


This works if there is a cpp file, which makes it inconvenient when used in a template-dependent context.
For obvious reasons, the current code cannot be placed in the header. Using static variables, in general, you can achieve a crooked solution to the problem (somehow checking duplicate constructor calls for all compilation units), but you don’t want to ... Is it possible to solve the problem in some more elegant way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shell_execute, 2016-01-30
@shell_execute

TLS-callback and use - www.unknowncheats.me/forum/c-and-c/84146-tls-callb... or stackoverflow.com/questions/14538159/about-tls-cal...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question