私はC++関数を使い、関数のオーバーロードを利用するC++テンプレート関数を書きたいと思っています。複数のC関数を内部的に呼び出すためのC++テンプレート関数の記述方法?
例えば、Iは、入力パラメータの種類に基づいて、fabs
又はmath.h
で定義さabs
への適切な呼び出しを行うテンプレートを使用して機能myAbs
を作成する必要があります。これを行う方法?
#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!
}
注:私は単に例として私の質問を説明するために使用しました。私はすでに、そのような関数「abs」が既に<cmath>
にあることを知っています。助け
#include <math.h>
#include <type_traits>
template<typename T>
T abs(T x)
{
if(std::is_same<T,double>::value)
{
//do double stuff
}
else if(std::is_same<T,float>::value)
{
//do float stuff
}
else
{
//deal with unsupported type
}
}
希望:
なぜ 'cmath'ではなく' math.h'をインクルードしていますか? –
@AndrewHenle:私はすでに記事の最後に、これは単なる例であるというメモとして述べました! – user4661268