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
.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments