This problem screams for a lookup table, where you store pointers to the various functions and they are keyed by the enumeration values.
If your enum
values are sequential (and no two enumeration constants share the same value), then you can build a lookup table as a simple 2D array:
enum x_t { X0, X1, X2, ..., NUM_X };
void (*lookup[NUM_X][NUM_X])(void) = {
{ NULL, X0_to_X1, X0_to_X2, X0_to_X3, ... },
{ X1_to_X0, NULL, X1_to_X2, X1_to_X3, ... },
{ X2_to_X0, X2_to_X1, NULL, X2_to_X3, ... },
...
};
That assumes you don’t have an "identity” function when your x
and y
are the same.
Then, you call the desired function by indexing into to table like so:
if ( x != y )
lookup[x][y]();
No, it isn’t pretty, but it beats nested switch
statements. You can hide that behind a macro or another function call if you wish.
If your enumeration values aren’t sequential then this particular implementation won’t work - you’d have to build your lookup table a different way, using lists or sparse matrices. But while the setup code may be tedious, it will greatly simplify the logic on the calling side.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…