String - Function

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.-
There is no way to access function names at runtime, they do not exist in the machine code. You have to compile them into the program, for example as a map that associates function names (as strings) with the functions themselves (as functions, or as function pointers, etc)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <functional>
#include <map>
#include <string>

void foo2(int a, int b)
{
    std::cout << a+b << '\n';
}
std::string foo(int x)
{
    if(x == 1)
        return "foo2";
}
int main()
{
    std::map<std::string, std::function<void(int, int)>> m;
    
    m["foo2"] = foo2;
   
    int x = 1;
    int y = 2;
    int z = 3;
    m[foo(x)](y, z);
}


online demo: http://ideone.com/J0qkj

Or you could have foo() return a function directly, to make it work as you described, with foo(x)(y,z)
Last edited on
Thanks for answering! Very clear, but the problem is that I need something where I don't define

m["foo2"] = foo2;

Because I have to do like 1000 times (m["foo3"] = foo3; .....) and obviously the names are not equals.
Part of my code
1
2
3
4
5
6
name = iter->movable->getName();
// Here I would like to use the name of the movable in the next if!
if(!name.isPlaying())
{
           name.trigger();
}

Topic archived. No new replies allowed.