Is there any way to print a C++ lambda expression and see a textual representation of the function it represents? Here is a simple example showing what I mean:
#include <iostream>
#include <functional>
const char *toString(const std::function<int(int)> &f)
{
// then a magic happens ...
return "if (...) { ... }";
}
int main(int argc, char **argv)
{
auto f1 = [=](int i){ if (i<5) {return 8*2;} else {return 2;} };
auto f2 = [=](int i){ if (i>3) {return i*i;} else {return 7;} };
std::cout << toString(f1) << "\n";
}
Any way to achieve this?
No, there is not. C++ is a language without any kind of reflection. It's impossible to implement such function.
The possible workarounds include puting the lambda sources in a string literal in your program or for example reading the source file from your program.