21

Been away from C++ for a few years and am getting a linker error from the following code:

Gene.h

#ifndef GENE_H_INCLUDED
#define GENE_H_INCLUDED

template <typename T>
class Gene {
    public:
    T getValue();
    void setValue(T value);
    void setRange(T min, T max);

    private:
    T value;
    T minValue;
    T maxValue;
};

#endif // GENE_H_INCLUDED

Gene.cpp

#include "Gene.h"

template <typename T>
T Gene<T>::getValue() {
    return this->value;
}

template <typename T>
void Gene<T>::setValue(T value) {
    if(value >= this->minValue && value <= this->minValue) {
        this->value = value;
    }
}

template <typename T>
void Gene<T>::setRange(T min, T max) {
    this->minValue = min;
    this->maxValue = max;
}

Using Code::Blocks and GCC if it matters to anyone. Also, clearly porting some GA stuff to C++ for fun and practice.

Flexo
  • 84,884
  • 22
  • 182
  • 268
Ryan_IRL
  • 545
  • 1
  • 5
  • 14
  • 1
    Exact error messages would be helpful. – sean e Jun 16 '09 at 02:40
  • 3
    possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Robᵩ May 09 '11 at 14:40

3 Answers3

28

The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).

Todd Gardner
  • 13,103
  • 37
  • 51
  • Thanks! I must have learned that at one point. Maybe now it will stick :D – Ryan_IRL Jun 16 '09 at 02:49
  • 2
    Or just implement the whole template in the header file. See the related question [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – RubenLaguna May 15 '12 at 06:12
5

Including the cpp file containing the implementations of the template class functions works. However, IMHO, this is weird and awkward. There must surely be a slicker way of doing this?

If you have only a few different instances to create, and know them beforehand, then you can use "explicit instantiation"

This works something like this:

At the top of gene.cpp add the following lines

template class Gene<int>;
template class Gene<float>;
ravenspoint
  • 16,826
  • 5
  • 55
  • 90
1

In if(value >= this->minValue && value <= this->minValue) the second minValue should be maxValue, no?

Echo what Sean said: What's the error message? You've defined and declared the functions, but you've not used them in anything anywhere, nor do I see an error (besides the typo).

Josh
  • 11,030
  • 11
  • 66
  • 104
Brian
  • 11
  • 1