0

I'm learning C++ and currently experiencing weird problem with Class template. This is my header file:

#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <list>

using namespace std;

template <int n>
class Vector {

public:
    list<float> coords;
    Vector();
    Vector(list<float> ncoords);
};

template <int n>
Vector<n>::Vector() {
    coords.assign(n, 0.0);
}
#endif

And this is my .cpp file:

#include "vector.h"
#include <list>

using std::ostream;
using namespace std;

template <int n>
Vector<n>::Vector(list<float> ncoords): coords {ncoords}{}

Everything works fine if I do Vector<2> vector;

But linker gives an error if I try to Vector<20> vector2 { list<float>{} };

Error message

undefined reference to `Vector<20>::Vector(std::list >)'

The question is - how can I solve this problem?

Ricardo Simmus
  • 334
  • 4
  • 19
  • 3
    You can't implement templates in .cpp-Files, you have to put that in the header. – ipc Mar 17 '13 at 20:11
  • Templates have to be implemented in headers. See [why](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – Synxis Mar 17 '13 at 20:15

1 Answers1

2

Templates have to be implemented inside header files. This is due to the way linking works. Read the exhaustive answer here carefully. And the next time search before asking.

Community
  • 1
  • 1
Alexander Shukaev
  • 16,674
  • 8
  • 70
  • 85