使用枚举来确定返回结果的类型(使用宏的黑客) [英] Use enum to determine type of return result ( a hack using Macro )

查看:271
本文介绍了使用枚举来确定返回结果的类型(使用宏的黑客)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多类型的游戏对象在一起是有一些方法。

所有关系都是由映射< K1,K2>

I have many types of game-object that are related together is some ways.
All relations is implemented by 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 所有关系查询: -

(只是一个例子,不需要注意所有细节)

Here is the hub class GameRelation that facilitates all relation query :-
(just an example, no need to pay attention to all detail)

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
};

上述宏扩展成如下: -

The above macro expands into something like :-

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

以下是如何使用(完整演示): -

Here is how it can be used (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;
}

经过一些测试,它的效果很好。每个人都很高兴与神奇的结果。

After some testing, it works good. Everyone is happy with the magical result.

然而,我的意识告诉我这是一个黑客。

它对内容辅助(例如智能感知)和自动

如果我想将其实现移到 .cpp ,我还需要 awesome 黑客 X-MACRO code>。

However, my conscious tell me that it is a hack.
It is also a little bad for content-assist (e.g. intellisense) and automatic refactoring.
I also need the awesome hacking X-MACRO if I want to move their implementation to .cpp.

问题:


    <有没有优雅(较少黑客)的方式?这是什么?

    否可以是一个有效的答案。
  • 当我需要这样(奇怪的)功能时,是否使用(专业)的方式进行X-MACRO ?

  • Is there any elegant (less hack) way? What is it?
    "No" can be a valid answer.
  • Is X-MACRO the (professional) way to go when I need such (strange) feature?

推荐答案

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()); 
}

这篇关于使用枚举来确定返回结果的类型(使用宏的黑客)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆