0

Possible Duplicate:
Why can templates only be implemented in the header file?
What is an undefined reference/unresolved external symbol error and how do I fix it?

I have defined a template class in a file.

point.h is

#ifndef POINT_H
#define POINT_H

using namespace std;

template <typename T, int size>
class point {
private:
    T coordinates[size];

public:
    point();
    void set_coordinates(const T *);
    void get_coordinates(T *);
};

#endif  /* POINT_H */

point.c is

#include "point.h"

template <typename T, int size>
point::point() {
    for (int i = 0; i < size; i++)
        coordinates[i] = 0;
}

template <typename T, int size>
void point<T, size>::set_coordinates(const T *coordinates) {
    for (int i = 0; i < size; i++)
        this->coordinates[i] = coordinates[i];
}

template <typename T, int size>
void point<T, size>::get_coordinates(T *coordinates) {
    for (int i = 0; i < size; i++)
        coordinates[i] = this->coordinates[i];
}

I am using this template as point<int, 2> p0;. But compiler gives error that point<int, 2> is not defined. I searched on this and found two solutions - 1. to use export variable. But I read that it is not supported by all compilers. So, I don't want to use that. 2. to create explicit class specializations like

template <> class point<int> {
    ...
}

But isn't there any other way to do this? (I mean in C++ standard containers, they might have used some technique to do this.)

Community
  • 1
  • 1
jyotesh
  • 330
  • 5
  • 17

3 Answers3

2

Read this and the next two FAQ questions - C++ FAQ

user93353
  • 13,733
  • 8
  • 60
  • 122
1

The solution of the c++ standard containers is keep everything in the header file.

Daniel
  • 30,896
  • 18
  • 85
  • 139
1

You should put all the definitions belonging to the template point (that is, including the member functions) to the point.h file and include it in any file that uses the point class, so that the compiler can instantiate it as needed. See this question for details.

The C++ compilers and linkers have means to avoid "multiple definitions" error on link (the ODR rule in the standard states this must be the case).

Community
  • 1
  • 1
jpalecek
  • 47,058
  • 7
  • 102
  • 144