Reputation: 116
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!
Upvotes: 5
Views: 1277
Reputation: 249462
C++ does not have reflection so you can't directly do this using the language alone. But you can do it by moving the function to a header file, #include
ing that file in your .cpp file, and also building the header file into an object file which makes it contents available as a constant string.
First, put this in foo.h
:
inline int functionToCopy()
{
int a{ 5 };
int b{ 6 };
return a + b;
}
Then, using the information from https://stackoverflow.com/a/46221837/4323 use objcopy
to create an object file:
objcopy --input binary --output elf64-x86-64 foo.h foo.o
Then change your main file like this:
#include <iostream>
#include <string_view>
#include "foo.h"
extern "C" const char* _binary_foo_h_start; // defined in foo.o
extern "C" const char* _binary_foo_h_size;
std::string_view printCopiedFunction()
{
return {_binary_foo_h_start, _binary_foo_h_size};
}
int main()
{
std::cout << functionToCopy() << '\n';
std::cout << printCopiedFunction() << '\n';
}
And link foo.o
into your executable at build time.
Note that objcopy
is available on Linux and some other systems, you may need to look for an equivalent on your platform. For example if you have xxd
: https://stackoverflow.com/a/411000/4323
On Windows you can embed the text file (which is the header file) as a "resource" in your executable, and load the resource at runtime, like this: Embed Text File in a Resource in a native Windows Application
Upvotes: 4