[英]How can I create template class member implementations in the cpp file for multiple types
I've got a template class called w32file which works with both wchar_t and char.我有一个名为 w32file 的模板 class,它适用于 wchar_t 和 char。 It's declared:
它宣布:
template <typename T>
class w32file { ... }
And it has many member methods such as this one:它有很多成员方法,比如这个:
inline bool isDirectory();
Now I know I could put all the implementation of these member methods in the header file and they'd then get compiled in to whatever object files use my template.现在我知道我可以将这些成员方法的所有实现放在 header 文件中,然后它们会被编译到使用我的模板的任何 object 文件中。 However, I don't really want this since this class is going to get used all over the place and it's going to lead to alot of repeated object code.
但是,我真的不想要这个,因为这个 class 会被到处使用,它会导致很多重复的 object 代码。
So at the moment, I have a cpp file which is linked to a static lib which does this:所以目前,我有一个链接到 static 库的 cpp 文件,它执行以下操作:
bool w32utils::w32file<wchar_t>::isDirectory()
{
auto dwAttr = GetFileAttributes(m_name.c_str());
return ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
}
bool w32utils::w32file<char>::isDirectory()
{
auto dwAttr = GetFileAttributes(m_name.c_str());
return ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
}
Now, my object code only get's created once, but I've had to create two copies of essentially the same method in my source code.现在,我的 object 代码只创建了一次,但我必须在我的源代码中创建两个基本相同方法的副本。 Does anyone know a way around this?
有谁知道解决这个问题的方法? Is there a way to get both implementations expanded into my object file in a templated way?
有没有办法以模板化的方式将这两种实现扩展到我的 object 文件中?
Define the function templated and use explicit template instantiation:定义模板化的 function 并使用显式模板实例化:
namespace w32utils
{
template <typename T>
bool w32file<T>::isDirectory()
{
const auto dwAttr = GetFileAttributes(m_name.c_str());
return ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
}
template class w32file<char>;
template class w32file<wchar_t>;
}
Note that I would strongly recommend putting that in the header and inlining it!请注意,我强烈建议将其放入 header 并内联!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.