Compile-time indexing magic?

Started by
11 comments, last by DevFred 14 years, 9 months ago
Is there any nifty preprocessor trick to generate an increasing index at compiletime? For instance, i want to do something like this: int one = AUTO_MAGIC_INDEX; int two = AUTO_MAGIC_INDEX; int three = AUTO_MAGIC_INDEX; int four = AUTO_MAGIC_INDEX; which would generate: one == 1; two == 2; three == 3; four == 4; What i want to use this for is to be able to have a class-member index.
Shields up! Rrrrred alert!
Advertisement
You can use __COUNTER__. This works on GCC 4.3+ as well.
If your compiler supports it:
int one = __COUNTER__;int two = __COUNTER__int three = __COUNTER__;int four = __COUNTER__;


EDIT: Ninja'd
In using GCC 4.1 im afraid, so it's not supported. Changing compiler is not an option either.

Is there any other way to simulate this behaviour with some macro tricks or something?
Shields up! Rrrrred alert!
enum {one = 1, two, three, four};
no fred, it has to automatically increase an assignable value, otherwise i might as well type the index numbers manually, and that's what i don't want to do.
Shields up! Rrrrred alert!
That's what his code is doing. Here's an equivalent example:
enum { blue = 1, red, green, yellow };

In this example, yellow has the value 4.
Quote:Original post by peter_b
Is there any other way to simulate this behaviour with some macro tricks or something?
Not that I'm aware of - this is why __COUNTER__ was invented.
Quote:it has to automatically increase an assignable value


This is what enum does.

Otherwise:
int getNextIndex() {  static count;  return count++;};



There is another option involving template meta magic, but it's hideously complex.
Yeah but the point is automatic generation of indexes.

Lets say we have a class:

template<int IDX>
class IndexedMember
{
enum {m_index = IDX};
};


Then it should be possible to use it like this:

class Whatever
{
IndexedMember<__COUNTER_EQUALENT__> m1;
IndexedMember<__COUNTER_EQUALENT__> m2;
IndexedMember<__COUNTER_EQUALENT__> m3;
}

I dont want to do:

class Whatever
{
IndexedMember<yellow> m1;
IndexedMember<red> m2;
IndexedMember<blue> m3;
}

because then i might aswell do:

class Whatever
{
IndexedMember<0> m1;
IndexedMember<1> m2;
IndexedMember<2> m3;
}

Which is the way it works right now, which is really bad since the project is huge and it causes many problems when new members are added and the updating of indices are overlooked.
Shields up! Rrrrred alert!

This topic is closed to new replies.

Advertisement