Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c++ - "Undefined symbols" linker error with simple template class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...