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

Categories

File main2.cpp:

#include "poly2.h"

int main(){
 Poly<int> cze;
 return 0;
}

File poly2.h:

template <class T>
class Poly {
public:
 Poly();
};

File poly2.cpp:

#include "poly2.h"

template<class T>
Poly<T>::Poly() {
}

Error during compilation:

src$ g++ poly2.cpp main2.cpp -o poly
/tmp/ccXvKH3H.o: In function `main':
main2.cpp:(.text+0x11): undefined reference to `Poly<int>::Poly()'
collect2: ld returned 1 exit status

I'm trying to compile above code, but there are errors during compilation. What should be fixed to compile constructor with template parameter?

See Question&Answers more detail:os

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

1 Answer

The full template code must appear in one file. You cannot separate interface and implementation between multiple files like you would with a normal class. To get around this, many people write the class definition in a header and the implementation in another file, and include the implementation at the bottom of the header file. For example:

Blah.h:

#ifndef BLAH_H
#define BLAH_H

template<typename T>
class Blah {
    void something();
};

#include "Blah.template"

#endif

Blah.template:

template<typename T>
Blah<T>::something() { }

And the preprocessor will do the equivalent of a copy-paste of the contents of Blah.template into the Blah.h header, and everything will be in one file by the time the compiler sees it, and everyone's happy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...