Hi,
Maybe is an easy question.

I have a function that return a String, and I would like to use this String like a name of another function, but I can't because obviously is a String :(.

For example, the function foo return a String foo2, and foo2 is a name of the function that takes parameters, so

(foo(x))(y z)

I hope that you understand my problem.
Thanks,
Alvaro.-

What you actually want to do is return a pointer to a function.

(Or, perhaps you really want to return a std::function<void(YType, ZType)>, which is different, but the first thing to learn is how function pointers work.)

Search for "function pointers" and learn how they work, they'll do what you want.

They'll do it without involving strings, by the way. There's no table of function names available at run-time, so that couldn't work. A function pointer is just the memory address of the first instruction in the function.

Edit: Interpreting your question less literally, it's also possible that you actually want runtime polymorphism, involving virtual functions and class inheritance. You should make sure you learn how these work, they could also be used to accomplish the goal, albeit less directly and more generally. And it's a very important part of C++.

Edited 4 Years Ago by Rashakil Fol

Hi,
Thank you very much for your answer. Very clear!
First, I'll try returning a pointer to a function. If a found any doubt, I am writing again :P!

Bests,
Alvaro.-

I read about pointer function, but it's not the thing that I need. Maybe I expresed my idea in a wrong way.

I copy an example to show you:

String name = iter->movable->getName();

// Here I would like to use the name of the movable object (String name) in the next if!
if(!name.isPlaying())
{
    name.trigger();
}

Is it clear now?

Is it clear now?

Very clear, but C++ isn't suited to this kind of dynamic programming. A better solution would be to return a reference to the object rather than the name of a variable (which is lost during compilation).

This article has been dead for over six months. Start a new discussion instead.