appending list at startup?

G

Gernot Frisch

Hi,

my problem in detail:
I want to make a macro:

DOUBLE(x);

in global space, that will do this:

std::map<const char*, void*> variables;

....

double x;
variables["x"] = &x;

However, I can't do the "variables["x"]" thingy in global space (out
of scope).
Is there any way to do this using constructors e.g.?

Thank you,
Gernot
 
K

Karl Heinz Buchegger

Gernot said:
Hi,

my problem in detail:
I want to make a macro:

DOUBLE(x);

in global space, that will do this:

std::map<const char*, void*> variables;

...

double x;
variables["x"] = &x;

However, I can't do the "variables["x"]" thingy in global space (out
of scope).
Is there any way to do this using constructors e.g.?

You can use a constructor for that. Why? Because the constructor
is a function (a very special one, but nevertheless it is a function)
that can be used to initialze a variable.
But it is not the only way to do that. Plain standalone functions
can also be called in an initialization and thus you can do:

double Register( const char* Name, double* Var )
{
variables[ Name ] = &Var;
return 0.0;
}

and create a macro, which does the equivalent of
double x = Register( "x", &x );

For the macro, you will need the stringize facility of macros,
look up what # and ## can be used for in macros.
 
G

Gernot Frisch

Gernot Frisch said:
Hi,

my problem in detail:
I want to make a macro:

DOUBLE(x);

in global space, that will do this:

std::map<const char*, void*> variables;

...

double x;
variables["x"] = &x;

However, I can't do the "variables["x"]" thingy in global space (out
of scope).
Is there any way to do this using constructors e.g.?

Whoha! I found it out!

// global container for variables
class __VAR_CONTAINER
{
public:
__VAR_CONTAINER() {data=new void* [10];num=0;}
void add(void* p) {data[num++] = p;}
void** data;
int num;
} __g_cont;

// temporary object wrapper, that adds t global container
template <class T> class __VAR_OBJECT
{
public:
__VAR_OBJECT(const T& t, __VAR_CONTAINER& cnt) {cnt.add((void*)&t);}
};

// Quicky
#define REGISTER(typ, var) typ var; __VAR_OBJECT<typ> reg ##var(var,
__g_cont);

REGISTER(double, __g_d);
REGISTER(int, __g_i);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top