I want to have a function template which takes a vector and an element and returns the position of this element in the vector. I want this function to be applicable for both int and std::string types. This is the function template definition:
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;
}
As you can see, I am checking the types initially so that I can use the appropriate comparison method. This works fine when I call with std::string type parameters but it gives the following error when I use it with double type:
 error C2228: left of '.compare' must have class/struct/union
and
see reference to function template instantiation 'int findElement<double>(const std::vector<_Ty> &,const T &)' being compiled
How do I solve this issue?
Thanks, Rakesh.
You should never have to check typeid when using templates. std::string defines == in the expected manner, so use it!
template<class T>
int findElement(const vector<T> &vec, const T &ele)
{
    for(size_t i = 0; i < vec.size(); i++)
    {
        if(ele == vec[i])
            return i;
    }
    return -1;
}
In general, if you need to special-case your templated function for a particular type, use a template specialization:
template<class T>
int findElement(const vector<T> &vec, const T &ele) {
    for(size_t i = 0; i < vec.size(); i++) {
        if(ele == vec[i])
            return i;
    return -1;
}
template<>
int findElement<std::string>(const vector<std::string> &vec, const std::string &ele) {
    for(size_t i = 0; i < vec.size(); i++) {
        if(ele.compare(vec[i]) == 0)
            return i;
    }
    return -1;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With