使用枚举确定返回结果的类型(使用宏进行黑客攻击)

时间:2017-04-22 07:46:48

标签: c++ enums macros c++14 x-macros

我有很多类型的游戏对象,它们在某些方面是相互关联的 所有关系都由Map<K1,K2>实施。

#include <vector>
using namespace std;

template<class K1,class K2> class Map{ //N:N relation
     public: std::vector<K2*> getK2(K1* k1){/* some code */return std::vector<K2*>();} 
     public: std::vector<K1*> getK1(K2* k2){/* some code */return std::vector<K1*>();}
     //... various function ...
};

这是促进所有关系查询的中心类GameRelation: - (只是一个例子,不需要注意所有细节)

class Human{};   class House{};    class Dog{};
class GameRelation{
    public:
    #define RELATION(A,B,EnumName) Map<A,B> Map##EnumName;  \
    enum EnumName##Enum{EnumName};   \
    std::vector<B*> getAllRight(EnumName##Enum e,A* a){  \
        return Map##EnumName.getK2(a);  \
    }
    //... various function ...
    RELATION(Human,House,Own) 
    //I can insert any relation that I want
};

上述宏扩展为: -

Map<Human,House> MapOwn; 
enum OwnEnum{Own};   
std::vector<House*> getAllRight(OwnEnum e,Human* a){  
    return MapOwn.getK2(a);  
}

以下是如何使用它(full demo): -

int main() {
    GameRelation gameRelation;
    std::vector<House*> houses=gameRelation.getAllRight(GameRelation::Own,new Human()); 
    //get all "House" that is "Own" by a "Human" 
    return 0;
}

经过一些测试,它运作良好。每个人都对这个神奇的结果感到满意。

然而,我有意识地告诉我这是一个黑客  内容辅助(例如智能感知)和自动重构也有点不好 如果我想将他们的实现移到.cpp,我还需要 awesome 黑客 X-MACRO

问题:

  • 有没有优雅(不那么黑客)的方式?它是什么?
    &#34;否&#34;可以是一个有效的答案。
  • 当我需要这种(奇怪的)功能时, X-MACRO 是(专业)的方式吗?

1 个答案:

答案 0 :(得分:1)

struct GameRelation{
    template <typename A, typename B>
    struct Relation {
        std::vector<B*> getAllRight(A* a) {
            return map.getK2(a);
        }

    private:
        Map<A, B> map;
    };

    Relation<Human, House> own;
};

int main() {
    GameRelation gameRelation;
    std::vector<House*> houses = gameRelation.own.getAllRight(new Human()); 
}