Template programming in C++

◇◆丶佛笑我妖孽 提交于 2019-12-11 13:14:54

问题


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

Consider the following files.

C.h

#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!


回答1:


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.



来源:https://stackoverflow.com/questions/3765556/template-programming-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!