我有一些模板代码,我宁愿存储在CPP文件中而不是标题中的内联.我知道只要您知道将使用哪些模板类型,就可以完成此操作.例如:
.h文件
class foo
{
public:
template <typename T>
void do(const T& t);
};
Run Code Online (Sandbox Code Playgroud)
.cpp文件
template <typename T>
void foo::do(const T& t)
{
// Do something with t
}
template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);
Run Code Online (Sandbox Code Playgroud)
注意最后两行--foo :: do模板函数仅用于int和std :: strings,因此这些定义意味着应用程序将链接.
我的问题是 - 这是一个讨厌的黑客还是会与其他编译器/链接器一起使用?我目前只在VS2008上使用此代码,但是想要移植到其他环境.
编译器说我在执行此操作时找不到该函数的引用:
// link.h
template <class T>
T *Link(T *&, T *(*)())
// link.cpp
template <class T>
T c:Link(T *&ChildNodeReference, T *(*ObjectCreator)()){
}
Run Code Online (Sandbox Code Playgroud)
如果我在标题内的类中实现它顺利进行.
拜托,我会在标题上工作,直到有人为此启发我.
C++中有些东西很奇怪.我知道,有这样的原因等等.即便如此,编译器也无法帮助你解决它-_-"