我有一些模板代码,我宁愿存储在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上使用此代码,但是想要移植到其他环境.