我希望编写一个 C++ 模板函数,它反过来使用一些“C”函数并利用函数重载。
比如我需要写一个函数myAbs
使用对 fabs
进行适当调用的模板或 abs
在 math.h
中定义, 基于输入参数类型。如何做到这一点?
#include <math.h>
template<typename T>
T abs(T x)
{
// I need to write an efficient code here!
// If it is 'double' and 'float' I may be able to compare the
// sizeof(Type) and call 'return fabs(x)' or 'return abs(x)'.
// But this is not a good solution as two types can be of same size!
}
注意:我只是以它为例来解释我的问题。我已经知道 <cmath>
中已经有这样一个函数“abs” .
最佳答案
模板可能不是这里的答案。考虑仅重载:
inline float myAbs(float x) { return fabsf(x); }
inline double myAbs(double x) { return fabs(x); }
关于c++ - 如何编写C++模板函数在内部调用多个C函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089819/