休息几周后,我试图通过这本书来扩展和扩展我对模板的知识模板 – 完整指南由 David Vandevoorde 和 Nicolai M. Josuttis 编写,我现在想要理解的是模板的显式实例化。
我实际上对该机制本身没有问题,但我无法想象我想要或想要使用此功能的情况。如果有人能向我解释这一点,我将不胜感激。
如果您定义了一个模板类,您只想为几个显式类型工作。
像普通类一样将模板声明放在头文件中。
就像普通类一样,将模板定义放在源文件中。
然后,在源文件的末尾,仅显式实例化您希望可用的版本。
愚蠢的例子:
// StringAdapter.h
template<typename T>
class StringAdapter
{
public:
StringAdapter(T* data);
void doAdapterStuff();
private:
std::basic_string<T> m_data;
};
typedef StringAdapter<char> StrAdapter;
typedef StringAdapter<wchar_t> WStrAdapter;
Source:
// StringAdapter.cpp
#include "StringAdapter.h"
template<typename T>
StringAdapter<T>::StringAdapter(T* data)
:m_data(data)
{}
template<typename T>
void StringAdapter<T>::doAdapterStuff()
{
/* Manipulate a string */
}
// Explicitly instantiate only the classes you want to be defined.
// In this case I only want the template to work with characters but
// I want to support both char and wchar_t with the same code.
template class StringAdapter<char>;
template class StringAdapter<wchar_t>;
Main
#include "StringAdapter.h"
// Note: Main can not see the definition of the template from here (just the declaration)
// So it relies on the explicit instantiation to make sure it links.
int main()
{
StrAdapter x("hi There");
x.doAdapterStuff();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)