“未定义符号”链接器错误与简单模板类 [英] "Undefined symbols" linker error with simple template class

查看:187
本文介绍了“未定义符号”链接器错误与简单模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已离开C ++几年,并从以下代码得到链接器错误:

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;
}

如果对任何人都重要,使用Code :: Blocks和GCC。此外,显然将一些GA的东西移植到C ++以便有趣和练习。

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

推荐答案

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

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

这篇关于“未定义符号”链接器错误与简单模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆