C ++: Error with Function Template

1

I've created a function using template, as shown in that answer , like this:

utilits.h

...
template<typename T> bool theres(T a, vector<T> b); 
...

utilits.cpp

...
template<typename T> bool theres(T a, vector<T> b)
{
    for(T& it : b)
        if (it == a)
            return 1;
    return 0;
}
...

main.cpp

...
vector<string> registro(0);
...
int main ()
{
    ...
    string nick = "far";
    ...
    if(theres(nick, registro)) // <- Erro aqui
    ...
}

I get the following error:

undefined reference to 'bool theres<std::string>(std::string, std::vector<std::string, std::allocator<std::string> >)'
    
asked by anonymous 27.06.2017 / 23:10

1 answer

2

The problem is that when you call a function that uses the template, it is replicated with the characteristics passed. For example, in this mine function:

template<typename T> bool theres(T a, vector<T> b); 

When I call it according to the question, the compiler identifies T as being string , then creates the function in the header file:

bool theres(string a, vector<string> b);

However, when trying to link to the .cpp file, it does not find the implementation of the theres(string, vector<string>) function, generating the error. The solution then put the implementation in the .h file, next to the declaration, doing so:

utilits.h

...
template<typename T> bool theres(T a, vector<T> b)
{
    for(T& it : b)
        if (it == a)
            return 1;
    return 0;
}
...

main.cpp

...
vector<string> registro(0);
...
int main ()
{
    ...
    string nick = "far";
    ...
    if(theres(nick, registro))
    ...
}

I hope I have helped someone who has the same problem.

    
28.06.2017 / 02:05