如何编写C++模板函数来内部调用多个C函数?

use*_*268 0 c c++ templates overloading

我希望编写一个C++模板函数,该函数反过来使用一些"C"函数并利用函数重载.

例如,我需要myAbs使用模板编写一个函数,这些模板根据输入参数类型进行适当的调用fabsabs定义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! 

}
Run Code Online (Sandbox Code Playgroud)

注意:我只是用它作为例子来解释我的问题.我已经知道这样的功能"abs"已经可用了<cmath>.

asc*_*ler 5

模板可能不是这里的答案.考虑只是重载:

inline float myAbs(float x) { return fabsf(x); }
inline double myAbs(double x) { return fabs(x); }
Run Code Online (Sandbox Code Playgroud)

  • 请注意模糊的重载.请参见http://stackoverflow.com/questions/1374037/ambiguous-overload-call-to-absdouble (2认同)