简洁的方法来计算#define

时间:2015-06-17 16:20:48

标签: c++ switch-statement c-preprocessor

我在生成的标题中有一组#define,如下所示:

#define SFX_SOIL_DESTROY_1 2
#define SFX_SOIL_DESTROY_2 14
#define SFX_SOIL_PLACE_1 32
#define SFX_SOIL_PLACE_2 33
#define SFX_WOOD_DESTROY_1 5

我有一个方法必须返回材质类型和声音类型的正确定义。这是一个长期,不确定的解决方案:

int getSfx (MaterialType material, SoundType sound)
{
     switch (material)
     {
         case SOIL:
         {
             switch (sound)
             {
                 case DESTROY:
                     return rand()%2 ?  SFX_SOIL_DESTROY_1 : SFX_SOIL_DESTROY_2;
                 case PLACE:
                 // And so on

是否有某种宏观黑客可以压缩这个?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

将其存储为数据查找要快得多,并且只需要处理一次(当它设置时)。因此,假设材料和声音或多或少是基于零的顺序(否则执行查找转换):

int soundLut [MAX_MATERIAL][MAX_SOUND][2] = {
    {        // SOIL
        {SFX_SOIL_DESTROY_1, SFX_SOIL_DESTROY_2},  // destroy
        {SFX_SOIL_PLACE_1, SFX_SOIL_PLACE_2},      // Place
        // etc - if only one effect, put 2 values the same
    },
    {        // WOOD
        // and so on
    }        
};

然后:

int getSfx (MaterialType material, SoundType sound)
{
    return soundLut [material][sound][rand()%2];
}

答案 1 :(得分:1)

也许您可以使用地图来实现与@Mike非常相似的解决方案(但可能更安全一些)。

void initialize()
{
    // This is your class member.
    // std::map< std::pair< MaterialType, SoundType >, std::pair< int, int > > sfxs;

    sfxs[ std::make_pair( SOIL, DESTROY ) ] = std::make_pair( SFX_SOIL_DESTROY_1, SFX_SOIL_DESTROY_2 );
    sfxs[ std::make_pair( SOIL, PLACE )   ] = std::make_pair( SFX_SOIL_PLACE_1,   SFX_SOIL_PLACE_2 );
    // ...
}

int getSfx( MaterialType aMaterial, SoundType aSound )
{
    const auto key = std::make_pair( aMaterial, aSound );
    if ( sfxs.find( key ) != sfxs.end() )
    {
        return ( rand() % 2 ) ? ( sfxs[ key ].first ) : ( sfxs[ key ].second );
    }
    return -1;
}