简体   繁体   中英

Template programming in C++

I am having trouble getting to grips with programming using templates in C++.

Consider the following files.

Ch

#ifndef _C_H
#define    _C_H

template <class T>
class C {
public:
    C();
    virtual ~C();
}
#endif _C_H

C.cpp

#include "C.h"

template <class T>
C<T>::C() {

}

template <class T>
C<T>::~C() {
}

I try instantiate an instance of C in a file called main.cpp.

#include "C.h"

int main(int argc, char** argv) {
    C<int> c;
}

I get the following error.

main.cpp undefined reference to `C<int>::C()'

I then run

g++ -o C.o C.pp
g++ -o main.o main.cpp

but get the error

main.cpp: undefined reference to `C<int>::C()'
main.cpp: undefined reference to `C<int>::~C()'

I am sure this probably an obvious mistake, but I am a real beginner at this so would appreciate any help.

Thanks!

When using templates, the source code is required to be available whenever the type is instantiated, because otherwise the compiler can't check that the template code will work for the given types. Dividing it into a .cpp and a .h file won't work, because the other .cpp files only know about the .h file.

You basically have to put everything in the .h file, or include an extra file with your implementation code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM