samedi 19 juin 2021

Print function contents as string but also be able to run it as code

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!





Aucun commentaire:

Enregistrer un commentaire