我在头文件中声明了一些小帮助函数。它看起来像这样:
//contents of foo.h
#ifndef FOO_H
#define FOO_H
void foo1(int a);
template <class mType>
void foo2( mType b);
#endif
//contents of foo.cpp
#include foo.h
void foo1(int a)
{
...
}
template <class mType>
void foo2( mType a)
{
...
}
通常只有函数模板时我会添加一个#include "foo.cpp"
在foo.h的末尾,使编译器在编译时可以看到模板函数的实现。但是,当混合功能模板和普通功能时,这种方法似乎不起作用。在这种情况下,如何解决模板函数和普通函数?
答案 0 :(得分:2)
您永远不应该包含cpp文件。
将模板的实现放在头文件中。如果你想将它分开,那么制作2个头文件。
//contents of foo.h
void foo1(int a);
template <class mType>
void foo2( mType a)
{
...
}
//contents of foo.cpp
#include foo.h
void foo1(int a)
{
...
}
(或者,有export
关键字,虽然没有主要编译器支持它,但它已在C ++ 11中删除了换句话说,不要使用它)