Mahesh Bansod
Mahesh Bansod

Reputation: 2033

Implementing a function which returns function definition as string

I'm making a program in which a function, say double f(double), is defined. I want to create a function(or a macro) codeToStr(f) which will return a std::string/const char* containing definition of the function f.
I believe that by using preprocessing directive something can be done but I can't figure out how.
Is there a way to do this besides using file IO and reading from the source file?

==
Reason for the question:
My university gave me the assignment to implement the "Trapezoidal rule" for numerical integration and they've asked us to hard-code the function f(x). After I submit the code, they will modify that function from the source code to test various cases. I'd like my output to have a way of displaying the function definition of the function that is going to be integrated. This is the reason why I want to implement codeToStr.

Upvotes: 1

Views: 82

Answers (2)

Sebastian
Sebastian

Reputation: 1974

Something like (untested):

#define xstr(a) str(a)
#define str(a) #a

#define FNDEF(ret,name,definition) \
    ret name definition \
    static char* name##_def xstr(ret) " " xstr(name) " " xstr(definition)

#define codeToStr(name) \
    (name##_def)

Then use

FNDEF(int, myfunction, (int param1, double param2), {do_something();})

in your .cpp file. And you can call

cout << codeToStr(myfunction) << endl;

anytime.

Upvotes: 1

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

You can try something like that:

#include <iostream>
#include <string>

#define real_stringify(s) #s
#define stringify(...) real_stringify(__VA_ARGS__)

#define MYFUNC double f(double d) { \
        return d*2; \
        }

MYFUNC

int main() {
        std::cout << f(5.5) << std::endl;
        std::string s = stringify(MYFUNC);
        std::cout << s << std::endl;
        return 0;
}

But this necessitate that the function is defined under the scope of the preprocessor. You can add more tricks to hide it as separating definition/declaration, etc.

Upvotes: 2

Related Questions