开发者

Mapping class to instance

I'm trying to build a simple entity/component system in c++ base on the second answer to this question : Best way to organize entities in a game?

Now, I would like to have a static std::map that returns (and even automatica开发者_运维技巧lly create, if possible).

What I am thinking is something along the lines of:

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

What would be the best way to achieve that?


Maybe this?

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

Then you can do:

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

Just out of curiosity, I checked the assembler code of this C++ code

#include <typeinfo>
#include <cstdio>

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

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

to be sure that it is really a constant. Assembler (stripped) outputted by GCC (without any optimisations):

.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

So it actually has to read the L__ZTI3Foo$non_lazy_ptr symbol (I wonder though that this is not constant -- maybe with other compiler options or with other compilers, it is). So a constant may be slightly faster (if the compiler sees the constant at compile time) because you save a read.


You should create some constants (ex. POSITION_COMPONENT=1) and then map those integers to instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜