(1)
// Foo.h
template<typename T>
class Foo
{
public:
void f();
};
// Foo.cpp
#include <iostream>
#include "Foo.h"
template<typename T>
void Foo<T>::f()
{
std::cout << "Foo<T>::f()/n";
}
// main.cpp
#include "Foo.h"
int main()
{
Foo<int> x;
x.f();
}
如上组织,会编译出错。
而如果把Foo.h和Foo.cpp合并在一起,就不会出现编译错误了。
#include <iostream>
template<typename T>
class Foo
{
public:
void f();
};
template<typename T>
void Foo<T>::f()
{
std::cout << "Foo<T>::f()/n";
}
int main()
{
Foo<int> x;
x.f();
}
这是正确的。
为什么呢?
(2)由于现在还没有支持template分离编译的编译器(记得目前还没有),因此我们常见的temp