开发者

How can I create template class member implementations in the cpp file for multiple types

开发者 https://www.devze.com 2023-03-19 03:25 出处:网络
I\'ve got a template class called w32file which works with both wchar_t and char.It\'s declared: template <typename T>

I've got a template class called w32file which works with both wchar_t and 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. 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.

So at the moment, I have a cpp file which is linked to a static lib which does this:

bool w32utils::w32file<wchar_t>::isDirectory()
{
    auto dwAttr = GetFileAttributes(m_name.c_str());
    return ((dwAttr & FILE_开发者_如何学PythonATTRIBUTE_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. Does anyone know a way around this? Is there a way to get both implementations expanded into my object file in a templated way?


Define the function templated and use explicit template instantiation:

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号