C++: Error with Function Template

Asked

Viewed 40 times

1

I created a function using feedback as demonstrated in that reply, in this way:

utilits. h

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

cpp utilities.

...
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> >)'
  • 3

    This information may be dated, but C++ handles templates via code substitution. This means that the template code needs to be in the same compilation unit as the type in the template; i.e., implementation in the .h

  • 1

    @Jeffersonquesado, thanks man, it’s working. I didn’t know I could implement the variable in the file .h

  • 1

    @Jeffersonquesado, why did you reply with a comment instead of a reply?

  • 1

    @Kylea found that there was not enough quality for response. Short and unexplained

1 answer

2

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

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

When I call her as per the question, the compiler identifies T as being string, then creates in the header file the function:

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

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

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’ve helped someone who has the same problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.