ベクトルと要素を取り、ベクトル内のこの要素の位置を返す関数テンプレートが必要です。この関数を int 型と std::string 型の両方に適用できるようにしたいと考えています。これは関数テンプレートの定義です:
template<class T>
int findElement(const vector<T> &vec, const T &ele)
{
for(size_t i = 0; i < vec.size(); i++)
{
if(typeid(ele) == typeid(std::string))
{
if(ele.compare(vec[i]) == 0)
return i;
}
else
{
if(ele == vec[i])
return i;
}
}
return -1;
}
ご覧のとおり、適切な比較方法を使用できるように、最初に型をチェックしています。これは、std::string 型パラメーターで呼び出すと正常に機能しますが、double 型で使用すると次のエラーが発生します。
error C2228: left of '.compare' must have class/struct/union
と
see reference to function template instantiation 'int findElement<double>(const std::vector<_Ty> &,const T &)' being compiled
この問題を解決するにはどうすればよいですか?
ありがとう、ラケシュ。