简体   繁体   中英

“Naming” template class instantiations

In my game engine, I've created a pretty funky component-based entity system which allows me to define entity types as a combination of components, specified as template arguments, eg:

typedef Entity<Locateable, Collidable, Renderable /* etc */ > SomeEntity;

This works fine, until I need to uniquely identify an instantiation of a template definition..

typedef Entity<Locateable, Collidable, Renderable> Missile;
typedef Entity<Locateable, Collidable, Renderable> Bullet;

typeid(Missile) == typeid(Bullet) // sad panda :( 

Obviously they are they same type, but I'd like them not to be, ideally I'd like to give each a string name, something like this:

// Invalid code...
typedef Entity<"Missile", Locateable, Collidable, Renderable> Missile;
typedef Entity<"Bullet", Locateable, Collidable, Renderable> Bullet;

That way I could access a static name() method later on. But that doesn't work because the strings need to be statically instantiated. I tried to do this too, but lambdas also aren't allowed...

// More invalid code...
typedef Entity<[]()-> char* { return "Missile"; }, Locateable, Collidable, Renderable> Missile;
typedef Entity<[]()-> char* { return "Bullet"; }, Locateable, Collidable, Renderable> Bullet;

So, my question is, is there some neat trick that will allow me to name the template definitions inline?

Instead of just using typedefs, you could use simple inheritance, maybe something like this:

class Missile : public Entity<Locateable, Collidable, Renderable>
{
public:
    static std::string name() { return "Missile"; }
};

class Bullet: public Entity<Locateable, Collidable, Renderable>
{
public:
    static std::string name() { return "Bullet"; }
};

The whole point of ECS is to be pointlessly dynamic. If it's not pointlessly dynamic, then why bother using ECS in the first place? Just use regular classes and composition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM