“Undefined symbols” linker error with simple template class

后端 未结 3 797
遥遥无期
遥遥无期 2020-11-30 09:43

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

tem         


        
相关标签:
3条回答
  • 2020-11-30 10:28

    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>;
    
    0 讨论(0)
  • 2020-11-30 10:29

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

    0 讨论(0)
  • 2020-11-30 10:32

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

    0 讨论(0)
提交回复
热议问题