简单模板类的"未定义符号"链接器错误

Rya*_*IRL 15 c++ templates unsatisfiedlinkerror

离开C++几年了,我从下面的代码中得到一个链接器错误:

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
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

如果对任何人都很重要,请使用Code :: Blocks和GCC.此外,明确地将一些GA内容移植到C++中以获得乐趣和练习.

Tod*_*ner 23

在实例化给定的模板类之前,必须包含模板定义(代码中的cpp文件),因此您必须在标头中包含函数定义,或者在使用类之前#include cpp文件(或者执行显式操作)实例化,如果你的数量有限).

  • 或者只是在头文件中实现整个模板.请参阅相关问题[为什么模板只能在头文件中实现?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) (2认同)

rav*_*int 5

包括包含模板类函数实现的 cpp 文件。然而,恕我直言,这既奇怪又尴尬。肯定有一种更巧妙的方法来做到这一点?

如果您只有几个不同的实例要创建,并且事先知道它们,那么您可以使用“显式实例化”

这工作是这样的:

在gene.cpp的顶部添加以下几行

template class Gene<int>;
template class Gene<float>;
Run Code Online (Sandbox Code Playgroud)