【发布时间】:2014-12-12 11:26:51
【问题描述】:
我正在尝试以下代码:
GeneralTemplate.h
#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
main.cpp
#include "GeneralTemplate.h"
#include <iostream>
int main()
{
GeneralTemplate<int> gInt;
gInt.arbitraryFunction(2.3);
return 0;
}
请注意,我没有任何类模板的成员函数的实现。但这不是问题。我知道该怎么做!如果我尝试编译 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
【问题讨论】:
-
_GENERATEMPLATE_H_是reserved identifier。您还应该检查 GCC 以查看它对代码的作用,以便您可以匹配给定的位置。 -
我只得到一个对析构函数的不明引用(clang++ 和 g++4.9.1,OS X 10.9)
-
糟糕!应该使用 GENERALTEMPLATE_H。但是改变它并不会改变错误。
-
@toutnom 您使用的是什么编译器/平台?
-
@toutnom,那么我认为@Snefel 和@AndreyT 是对的! (PS:可以用
throw()(或C++11中的noexcept)标记函数,并且仍然可能具有相同的行为,即不超过1个dtor调用。
标签: c++ templates undefined-reference