Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template for string and int in C++

Tags:

c++

templates

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.

like image 859
Rakesh K Avatar asked Dec 08 '22 16:12

Rakesh K


1 Answers

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;
}
like image 136
nneonneo Avatar answered Dec 26 '22 10:12

nneonneo