0
struct object
{
    void function()
    {
        std::cout << "function" << std::endl;
    }
};

int main()
{
    // create vectors for objects and functions)
    std::vector<object*> objectvec;
    std::vector<void*> functionlist;
    objectvec.push_back(new object);

    // create a pointer to an object's function

    void (object::* ptfptr_function) (void) = &object::function;
    functionlist.push_back(&ptfptr_tryfunc);

    // how do I call "functionvec[0]->tryfunc()" using the functionlist?
    // (following line does nothing:)

    functionlist[0];
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084

1 Answers1

2

You want this:

std::vector<void(object::*)()> functionlist;    // container

functionlist.push_back(&object::function);      // add pointer-to-member-fn

(objectvec[0]->*functionlist[0])();             // invoke ptmf on an instance
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • This is very helpful, thank you. I suppose it could be placed on a loop as thus: for (int i = 0; i<= NUM; i++) { (objectvec[i]->*functionlist[i])(); } But can it simply be a pointer to a specific member's function without the compound function "(objectvec[i]->*functionlist[i])()". as in one call functionlist[i](); – user2852086 Oct 06 '13 at 19:07
  • @user2852086: No. Member functions are not functions. You cannot *call* a member function. You can only combine it with an object to invoke it *on that object*. Think of it as an "offset into your class". If you want to bind a specific object to a member function, use `std::mem_fn` or `std::bind` or a lambda. – Kerrek SB Oct 06 '13 at 19:09
  • may I observe an example of "std::mem_fn or std::bind or a lambda" please? – user2852086 Oct 06 '13 at 19:37
  • @user2852086: Can you search for it yourself? It's a bit much for the comments. `auto f = std::mem_fn(&object::function)` becomes a function of `object&`, e.g. usage as `f(objectvec[0])`. With `bind` you can create a callable entity, like `auto g = std::bind(&object::function, objectvec[0]);`, usage: `g()`. – Kerrek SB Oct 06 '13 at 19:48