C ++ element function pointers

I am making a small game in C ++, and I find pointers to class functions. I have no idea for them to work correctly, but here is my attempt.

// A struct where the function pointer will be stored for the call
// By the way, is there a way to do the same thing with classes ?
// or are structs still fine in C++ ? (Feels like using char instead of string)
typedef struct      s_dEntitySpawn
{
  std::string       name;
  void          (dEntity::*ptr)();
} t_dEntitySpawn;

// Filling the struct, if the entity classname is "actor_basicnpc",
// then I would like to do a call like ent->spawnBasicNPC
t_dEntitySpawn      dEntitySpawns[] = {
  { "actor_basicnpc", &dEntity::spawnBasicNPC },
  { 0, 0 }
};

// This is where each entity is analyzed
// and where I call the function pointer
void            dEntitiesManager::spawnEntities()
{
  dEntity       *ent;
  t_dEntitySpawn    *spawn;

    [...]

      // It makes an error here, feels very weird for me
      if (!spawn->name.compare(ent->getClassname()))
        ent->*spawn.ptr();

    [...]
}

Could you give me good advice on the correct way to implement them?

Sincerely.

+3
source share
2 answers

I think the string you are looking for is

(ent->*(spawn->ptr))();

Cut it. First, we need to go to the actual pointer of the member function, which

spawn->ptr

Since here spawnis a pointer, and we must use ->to select fields ptr.

, , ent -:

ent->*(spawn->ptr)

, , ++, -. - ++ , -,

(ent->*(spawn->ptr))();

, ++, .: -)

, ++, typedef struct.

struct t_dEntitySpawn {
  std::string name;
  void (dEntity::*ptr)();
};

, !

+5

- , C ++, ++, .:-P

" C", , , , C polymorphism C. ++, ++ , , . - , ++ .

, , , , ++.

-. . , . (, !)

class EntitySpawn 
{
public:
    void spawn_entity()
    {
        spawn();
    }

private:
    // std::string name; // Not necessary for polymorphism to work
    virtual void spawn() = 0;
};

class ActorBasicNPC : public EntitySpawn
{
private:
    virtual void spawn() { /* implementation specific to ActorBasicNPC */ }
};

void test_spawn(EntitySpawn& es)
{
    // This will call the correct implementation of spawn(),
    // even though we only got a reference to an EntitySpawn.
    es.spawn_entity();
}

int main()
{
    ActorBasicNPC npc;
    // Calls ActorBasicNPC::spawn() even though only a
    // reference to EntitySpawn was passed.
    test_spawn(npc);
};
+3

All Articles