tou*_*nom 6 c++ templates undefined-reference
我正在尝试以下代码:
#ifndef _GENERATEMPLATE_H_
#define _GENERATEMPLATE_H_
#include <iostream>
template <class T>
class GeneralTemplate
{
public:
GeneralTemplate();
GeneralTemplate(const GeneralTemplate &g);
~GeneralTemplate();
GeneralTemplate& operator= (GeneralTemplate const& g);
template <class M>
void arbitraryFunction(const M &m);
};
#endif
Run Code Online (Sandbox Code Playgroud)
#include "GeneralTemplate.h"
#include <iostream>
int main()
{
GeneralTemplate<int> gInt;
gInt.arbitraryFunction(2.3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我没有任何类模板的成员函数的实现.但那不是问题.我知道怎么做!如果我尝试编译main.cpp,我应该得到一个链接错误,这就是我得到的.问题是为什么它试图找到两次析构函数(下面的两行错误).
$g++ main.cpp
/tmp/cckrdPCs.o: In function `main':
main.cpp:(.text+0x13): undefined reference to `GeneralTemplate<int>::GeneralTemplate()'
main.cpp:(.text+0x34): undefined reference to `void GeneralTemplate<int>::arbitraryFunction<double>(double const&)'
main.cpp:(.text+0x45): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
main.cpp:(.text+0x61): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
它很可能与异常安全有关.如果arbitraryFunction抛出异常,则需要展开堆栈,这意味着gInt需要尽早销毁.由于这一切都在发生main,没有进一步的展开将会发生,它是否真的需要两次调用析构函数是值得怀疑的......但是你所观察到的行为并非完全脱离困境.