I would like to make a function that can print the contents of another function without breaking the functionality of the copied function.
For example:
int functionToCopy() { int a{ 5 }; int b{ 6 }; return a + b; } void printCopiedFunction() { some magical code to print the contents of the first function; } int main() { std::cout << functionToCopy() << '\n'; std::cout << printCopiedFunction() << '\n'; return 0; } Output:
11 int functionToCopy() { int a{ 5 }; int b{ 6 }; return a + b; } I'm only a beginner and C++ is my first language. I've done a lot searching and thinking but the only way I could think of is just literally copying the function and making a 2nd function a string, which would double my code and I'd rather avoid that. The program I'd like to do this with currently has 26 functions that would need copying like that so a single function that can be reused would be much preferred.
std::string copiedFunction() { std::string str{ R"( int functionToCopy() { int a { 5 }; inb b { 6 }; return a + b; })" }; return str; } Any help is much appreciated! This is the only time I've ever asked for help like this on a forum but I think this is just beyond my abilities at this point. I understand this may not be possible or it may be very complex and just beyond my scope at this time. Thank you in advance!
reflection. But I am not knowledgeable enough to provide an answer. You could just have your program read it's own source files but that's weak.__FUNCTION__, get file name from__FILE__. Read the file and print the function. But you would have to call print from the function itself.