使用宏编译时使用用户定义的数学函数,或者简单地使用 c++ 中标准数学库中的函数
Using user defined math functions when compiled with a macro, or simply use the function from a standard math library in c++
我有自己的 f_sin(x) 函数实现(类似于 中 sin(x) 的实现),我想在使用名为 MYMATH 的宏编译时使用它。如果未定义 MYMATH,我想使用 math.h
中的函数 sin(x)
关于如何进行的任何线索?
请注意,我无法更改 f_sin(x) 或 sin(x) 的函数定义中的任何内容。
你可以这样做:
double sin_wrapper(double x) {
#ifdef MYMATH
return f_sin(x);
#else
return std::sin(x);
#endif
}
然后将所有对 sin
的调用替换为对该包装器的调用。
您可以尝试为每个函数使用一个宏,然后根据您的宏 MYMATH 定义它。此外,如果您更喜欢避免使用此类宏,则可以使用通用 lambda 作为包装器。
MyMath.hpp
1.- 每个函数都有宏
#ifdef MYMATH
#define imp_sin(x) f_sin(x)
#else
#include <cmath>
#define imp_sin(x) std::sin(x)
#endif
2。使用通用 lambda (C++ 14)
#define glambda(x) [](auto y){ return x(y); }
#ifdef MYMATH
auto imp_sin = glambda(f_sin);
#else
#include <cmath>
auto imp_sin = glambda(std::sin);
#endif
#undef glambda //Or not if you want to keep this helper
用法main.cpp
#include "MyMath.hpp"
int main(int, char**) {
imp_sin(3.4f);
return 0;
}
我有自己的 f_sin(x) 函数实现(类似于 中 sin(x) 的实现),我想在使用名为 MYMATH 的宏编译时使用它。如果未定义 MYMATH,我想使用 math.h
中的函数 sin(x)关于如何进行的任何线索?
请注意,我无法更改 f_sin(x) 或 sin(x) 的函数定义中的任何内容。
你可以这样做:
double sin_wrapper(double x) {
#ifdef MYMATH
return f_sin(x);
#else
return std::sin(x);
#endif
}
然后将所有对 sin
的调用替换为对该包装器的调用。
您可以尝试为每个函数使用一个宏,然后根据您的宏 MYMATH 定义它。此外,如果您更喜欢避免使用此类宏,则可以使用通用 lambda 作为包装器。
MyMath.hpp
1.- 每个函数都有宏
#ifdef MYMATH
#define imp_sin(x) f_sin(x)
#else
#include <cmath>
#define imp_sin(x) std::sin(x)
#endif
2。使用通用 lambda (C++ 14)
#define glambda(x) [](auto y){ return x(y); }
#ifdef MYMATH
auto imp_sin = glambda(f_sin);
#else
#include <cmath>
auto imp_sin = glambda(std::sin);
#endif
#undef glambda //Or not if you want to keep this helper
用法main.cpp
#include "MyMath.hpp"
int main(int, char**) {
imp_sin(3.4f);
return 0;
}