将类映射到实例

时间:2010-07-18 18:47:07

标签: c++ static map

我正在尝试用这个问题的第二个答案在c ++中构建一个简单的实体/组件系统:Best way to organize entities in a game?

现在,我想要一个返回的静态std :: map(如果可能的话,甚至会自动创建)。

我在想的是:

PositionComponent *pos = systems[PositionComponent].instances[myEntityID];

实现这一目标的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

您应该创建一些常量(例如POSITION_COMPONENT = 1),然后将这些整数映射到实例。

答案 1 :(得分:1)

也许这个?

std::map< std::type_info*, Something > systems;

然后你可以这样做:

Something sth = systems[ &typeid(PositionComponent) ];

出于好奇,我检查了这个C ++代码的汇编代码

#include <typeinfo>
#include <cstdio>

class Foo {
    virtual ~Foo() {}
};

int main() {
    printf("%p\n", &typeid(Foo));
}

确保它确实是一个常数。 GCC输出的汇编(剥离)(没有任何优化):

.globl _main
_main:
LFB27:
        pushl   %ebp
LCFI0:
        movl    %esp, %ebp
LCFI1:
        pushl   %ebx
LCFI2:
        subl    $20, %esp
LCFI3:
        call    L3
"L00000000001$pb":
L3:
        popl    %ebx
        leal    L__ZTI3Foo$non_lazy_ptr-"L00000000001$pb"(%ebx), %eax
        movl    (%eax), %eax
        movl    %eax, 4(%esp)
        leal    LC0-"L00000000001$pb"(%ebx), %eax
        movl    %eax, (%esp)
        call    _printf
        movl    $0, %eax
        addl    $20, %esp
        popl    %ebx
        leave
        ret

所以它实际上必须读取L__ZTI3Foo$non_lazy_ptr符号(我想知道这不是常量 - 可能与其他编译器选项或其他编译器,它是)。因此,常量可能稍快一些(如果编译器在编译时看到常量),因为您保存了读取。