Thread: Variable Function?

  1. #1
    Rabite SirCrono6's Avatar
    Join Date
    Nov 2003
    California, US

    Question Variable Function?

    I was wondering if it is possible to call a variable function? Such as:
    std::string Func = "CallThisFunction";
    It would call CallThisFunction... I doubt it's possible, but if it is it will save me quite a bit of coding

    - SirCrono6
    From C to shining C++!

    Great graphics, sounds, algorithms, AI, pathfinding, visual effects, cutscenes, etc., etc. do NOT make a good game.
    - Bubba

    IDE and Compiler - Code::Blocks with MinGW
    Operating System - Windows XP Professional x64 Edition

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    One way is to set up a map, so long as all the called functions have the same prototype.

    Something along the lines of
    #include <map>
    typedef void (*fntype)(void);
    std::map<std::string,fntype> mapping;
    // then set things up
    mapping["CallThisFunction"] = func;
    // then use is
    mapping["CallThisFunction"] ();
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2003
    ...ahhh, I was wondering how to conjure up an associative array in C++. You can do something similar with two 'parallel arrays' if the STL is too frightening or is hidden behind a cloud of ignorance:

    string names[3] = {"func1", "func2", "func3"};
    void (*pfuncs[3])(void) = {func1, func2, func3};
    string f = "func2";
    for(int i = 0; i < (sizeof names/sizeof names[0]); i++)
    	if(names[i] == f)
    A function pointer starts with the pointer:


    and then you add parentheses around it:


    and then you add the return type and the parameter type(s):

    void (*pfunc)(void)

    For an array of function pointers, you add in the array size:


    That also requires that the return types and parameter types are identical for all your functions.
    Last edited by 7stud; 02-24-2005 at 03:08 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  5. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM