看到下面的代码,请清除我的疑惑。显式模板实例如何影响链接器可以找到的内容?
由于ABC是一个模板,它为什么不显示一个错误,当我们把TEST.CPP的ABC类的成员函数的定义是什么?
如果我把test.cpp代码放在test.h和remve 2中,那么它工作正常。为什么?
。
// test.h
template <typename T>
class ABC {
public:
void foo(T&);
void bar(T&);
};
// test.cpp
template <typename T>
void ABC<T>::foo(T&) {} // definition
template <typename T>
void ABC<T>::bar(T&) {} // definition
template void ABC<char>::foo(char &); // 1
template class ABC<char>; // 2
// main.cpp
#include "test.h"
int main() {
ABC<char> a;
a.foo(); // valid with 1 or 2
a.bar(); // link error if only 1, valid with 2
}
你为什么要问?他们是两个毫不相关的陈述。 – 2010-04-29 07:29:14
@Dennis Zickefoose:大家都是初学者在某些点 – ereOn 2010-04-29 07:33:24
@ereOn:是的,但为什么他问能走很长的路向建议适当的解决办法回答他的问题时采取。 – 2010-04-29 07:57:27