As far as I can understand, the function that you wrote above is basically generating code
O_o
Well, that is right, but I think you got there for the wrong reasons.
In fairness to you, "a function is literally created by the other function" is also wrong.
The code uses generative facilities in that `std::bind' and `std::function' use generative facilities, but there is no generative code in the example.
[Edit]
Well, I guess you could argue that the particular flavor of class, similar in nature to `STest', return by the `makeFunction' is generated, but that happens during compilation, and the generation only happens once.
[/Edit]
That code simply binds a value as a parameter to an existing function which just happens to be an anonymous function.
You can see how this works out in my example code (#1).
Let me explain, the anonymous function within `makeFunction' isn't created on the fly during program execution; the function exists during compilation and is only bound to values during program execution. Basically, the compiler creates a function of the `void(double, double);' variety and binds the first parameter and a pointer to that function within a class which then calls that function with the stored parameter on demand.
If it helps, you can think of that code as doing the same as my example code (#2).
The higher level facilities such as `std::bind' and `std::function' just make this code a lot simpler.
The use of the lambda function just prevents you from having to jump through hoops such as creating a named function.
how can I use this kind of lambda programming to use the string variable that contains the name of a function to call actual real function that this name is referring to?
You can't. Well, you can't without also using something like iMalc posted or doing it manually.
As weird as it may seem, the C/C++ compiler doesn't know the names of functions as strings. Even the processor directive `__FUNCTION__' isn't guaranteed to be meaningful.
*shrug*
I think the point was more not separating the naming from the mapping.
Code:
my_map["func_name"] = [=](double x){std::cout<<"function "<<x<<std::endl;}; // or similar
Soma
Code:
#include <functional>
#include <iostream>
void Go
(
double f1
, double f2
)
{
using namespace std;
cout << "function " << f1 << " prints " << f2 << "*" << f1 << " = " << f2 * f1 << endl;
}
std::function<void(double)> makeFunction
(
double f1
)
{
using namespace std;
return(bind(&Go, f1, placeholders::_1));
}
int main()
{
std::function<void(double)> s1(makeFunction(5));
s1(4);
makeFunction(1)(6);
return(0);
}
Code:
#include <iostream>
struct STest
{
STest
(
double f
):
m(f)
{
}
double operator ()
(
double f
)
{
using namespace std;
cout << "function " << m << " prints " << f << "*" << m << " = " << f * m << endl;
}
double m;
};
int main()
{
STest s1(5);
s1(4);
STest(6)(1);
return(0);
}