0

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?

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    No, is the simple answer. What you are asking for seems equivalent to a disassembler for C++. Something that is impossible. – john Apr 18 '20 at 08:36
  • 1
    You can write your lambda body in macro expression. But this is will be only string representation of code without resolving type, functions and etc. – Mister_Jesus Apr 18 '20 at 08:39

1 Answers1

1

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111