Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Defining methods of class with template parameters

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...