-1

I am trying to implement a Template function of the Manhattan Distance for vectors that have any type (int, float etc) of coordinates, in C++.

So I have this:

template <typename T>
T manhattan_distance(std::vector<T> v1, std::vector<T> v2) { 
    //implementation
}

When trying to use it (in another file), I do as follows:

std::vector<int> v1 = [1,2,3];
std::vector<int> v2 = [4,5,5];
int res = manhattan_distance(v1,v2);

When make-ing, I get this error:

 undefined reference to `int manhattan_distance<int>(std::vector<int, std::allocator<int> >, std::vector<int, std::allocator<int> >)'

What is the issue? The function is not in a class. Am I missing something? Thanks in advance!

Zap
  • 325
  • 1
  • 6
  • 23
  • Is your function declared in a header file and defined in a cpp file? – NathanOliver Oct 10 '19 at 21:00
  • Yes, indeed. In the `.h` file it's `template T manhattan_distance(std::vector v1, std::vector v2);` and in the `.cpp` file as above. – Zap Oct 10 '19 at 21:01
  • 1
    Templates (for the most part) need to be defined in the header file because of the way C++ and templates work – NathanOliver Oct 10 '19 at 21:04

1 Answers1

1

The template code must be available when compiling your cpp file, you cannot just have the declaration in the header.
The reason is that the compiler does not generate any code when it reads the template; only when you use it, it will build an instance of it. The declaration of the template function is insufficient to build the code.

You need to have the implementation inside the header file too. That is a well-known disadvantage of template programming.

Aganju
  • 6,295
  • 1
  • 12
  • 23