Quote:Original post by ZealousEngine
There are many times where I find myself writing dozens of lines of code where there is only a minor difference from line to line (a name for example). A good example is my function map. I have a list of component names, and I want to map each unique name to a unique function (since its faster than a big switch statement)...
Quote:
mFuncMap[meshId] = &funcMesh
mFuncMap[particleEffectId] = &funcParticleEffect
mFuncMap[rigidBodyId] = &funcRigidBody
In the above case each unique component (mesh, particle effect, ect..) maps to a unique function. But it really bugs me that I have to write all this out long hand, when there SHOULD be a way to create some kind of loop...
Quote:
for ( int i = 0; i < numComponents; ++i ) {
mFuncMap[getComId(i)] = &func'MACRO_getComName(i)';
}
Is there anyway to do the above?
Thanks!
I usually achieve this like so:
#define LIST_MY_STUFF( F, A, B, C ) \ F( mesh, Mesh, A, B, C ) \ F( particleEffect, ParticleEffect, A, B, C ) \ F( rigidBody, RigidBody, A, B, C ) //#define FUNC_MAP( L, U, A, B, C ) \ mFuncMap[L##Id] = &func##U; //LIST_MY_STUFF( FUNC_MAP, unused, unused, unused );
^^ A, B and C are just there if you need to pass in any arguments. They're not used so I've just chucked 'unused' there - you can put any crap you want (boost chooses to use ~ for unused macro arguments) or if none of your macros require extra arguments you can get rid of A,B,C altogether (or if you need more than 3 arguments you can add D,E,F,G...).
If you need to call another function for each thing in the list, just make a new macro like FUNC_MAP, and then do the for-each using LIST_MY_STUFF.
[EDIT]N.B. if you're copy/pasting my code, I had to insert a space after each back-slash to make the forum accept the code ;) Make sure to remove these spaces if you want to try and compile it.
[EDIT2] I'm sure this can be done with boost as well, but IMO this is a lot simpler and easier for non-boost-acquainted people to come to grips with.
[EDIT3] I'm not sure if this is portable, but it works with MSVC 6 - MSVC 2008 (I haven't tested with GCC, etc.)