0

I'm trying to create a sameElements function, and i'm doing it this way:

util.h

#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED

#include <vector>

class Util {
public:
  template<typename T>
  static bool sameElements(const std::vector<T> t1,const std::vector<T> t2);
private:
};

#endif

util.cpp

#include "util.h"

template<typename T>
bool Util::sameElements(const std::vector<T> t1,const std::vector<T> t2) {
  return false; // Changed the actual logic to focus in the real problem
}

So, i am calling this method as follows from main.cpp

#include "util.h"

using namespace std;

int main()
{
    std::vector<int> v1 = {1,2,3,4};
    std::vector<int> v2 = {1,2,4,3};
    std::cout << "sameElements(v1, v2): " << (Util::sameElements(v1, v2)) << std::endl;

    return 0;
}

I expect to print "0" (false) but i'm getting this exception instead:

jscherman@jscherman:~/Workspace/cproject/src$ g++ main.cpp  util.cpp --std=c++11 && ./a.out
main.cpp:(.text+0x55d): undefined reference to `bool Util::sameElements<int>(std::vector<int, std::allocator<int> >, std::vector<int, std::allocator<int> >)'
collect2: error: ld returned 1 exit status

Any idea what's going on?

jscherman
  • 5,839
  • 14
  • 46
  • 88
  • 1
    Well, it doesn't work this way. In a typical C++ compiler _definitions_ of template methods must be accessible in the point of usage. Otherwise the code won't be generated – user3159253 May 26 '16 at 18:09
  • 1
    That's why in a typical C++ STL implementation all template classes methods are defined either in class definition or in a `.tcc` file, included at the bottom of `.h` file. So you have to do something similar: include `util.cpp` from `util.h`. – user3159253 May 26 '16 at 18:11
  • 1
    Alternatively you might explicitly instantiate Util::sameElements for a number of required types, and then the linker will succeed – user3159253 May 26 '16 at 18:14
  • 1
    take a look at [this question](http://stackoverflow.com/questions/7182359/template-instantiation-details-of-gcc-and-ms-compilers) – user3159253 May 26 '16 at 18:18
  • @user3159253 thanks ! but i was trying to avoid creating a new instance of the object every time that i want to call this method. regarding your previous comment, how is that including `util.cpp` in `util.h` will help? It sounds weird to me (btw i am totally new at c++), could you explain a little more? :) – jscherman May 26 '16 at 18:23
  • I coulnd't solve the problem with the "duplicated" post. I really don't know how to solve this and i've been struggling for days. I was expecting a little help – jscherman May 28 '16 at 20:29
  • 1
    Since I can't add an answer here, just a suggestion: just define your template class and all its methods in a single `util.h` file and include it into your `main.cpp`. You don't need `util.cpp` at all. You're guaranteed to get a single instance of `Util::sameElements(....)` – user3159253 May 30 '16 at 14:35

0 Answers0