Jump to content
  • Advertisement
Sign in to follow this  
CJWR

c++: is there a way to do this?

This topic is 4863 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

this was something i was thinking about last night, and i was wondering if there was anyway to do it. lets say we have 3 functions: fun1() fun2() fun3() now when the program loads, it asks the user what function he or she want wants to have run. if the user enters "fun1" than the program runs fun1(). is there anyway to do this, other than with switch/if statements? somesort of way to call a function whose name is inside of a string for example? hopefully someone understands what i'm talking about, even if there is no way to do this. i can't really see to many uses for it, i was just wondering if it could be done. thank you for your time.

Share this post


Link to post
Share on other sites
Advertisement
You can set up a std::map to create an association between a string and a function pointer, though that seems like not what you have in mind. For what I think you're thinking of, you would need reflection/introspection, which C++ does not possess natively, though some languages like Java or C# could do so.

Share this post


Link to post
Share on other sites
Quote:
Original post by MikeWulf
Um, first, why do you need it to be outside of if/switch's? It may be the most elegant approch.

No, it's not. Using a dictionary (std::map) is the most elegant approach.

typedef void (*function)();
std::map<std::string, function> function_map;
function_map["fun1"] = fun1;
function_map["fun2"] = fun2;
function_map["fun3"] = fun3;

std::string function_name = "fun2";
function_map[function_name]();

Share this post


Link to post
Share on other sites
Quote:
Original post by MikeWulf
Um, first, why do you need it to be outside of if/switch's? It may be the most elegant approch.


well, if you have hundreds of functions, that's one big if statement. but this was just something i was wondering about.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!