我意识到我必须将以下代码(用于模板专业化)放在 CPP 文件而不是头文件中?有什么办法可以在头文件中制作它吗?
template<> inline UINT AFXAPI HashKey<const error_code &> (const error_code & e)
{
// Hash code method required for MFC CMap.
// This hash code generation method is picked from Joshua Bloch's
// Effective Java.
unsigned __int64 result = 17;
result = 37 * result + e.hi;
result = 37 * result + e.lo;
return static_cast<UINT>(result);
}
Run Code Online (Sandbox Code Playgroud)
如果将上述函数放在 error_code.h 中,我会得到错误
错误 C2912:显式特化;'UINT HashKey(const error_code &)' 不是函数模板的特化
关于为什么我需要进行上述模板专业化的一些参考资料。http://www.codeproject.com/KB/architecture/cmap_howto.aspx。以下代码摘自文章,是MFC源代码的一部分。
// inside <afxtemp.h>
template<class ARG_KEY>
AFX_INLINE UINT AFXAPI HashKey(ARG_KEY key)
{
// default identity hash - works for most primitive values
return (DWORD)(((DWORD_PTR)key)>>4);
}
Run Code Online (Sandbox Code Playgroud)
我认为你必须在头文件中执行此操作。
//template non-specialized version which you forgot to write!
//compiler must know it before the specialized ones!
template<typename T> inline UINT AFXAPI HashKey(T e);
//then do the specializations!
template<> inline UINT AFXAPI HashKey<const error_code &> (const error_code & e)
{
// Hash code method required for MFC CMap.
// This hash code generation method is picked from Joshua Bloch's
// Effective Java.
unsigned __int64 result = 17;
result = 37 * result + e.hi;
result = 37 * result + e.lo;
return static_cast<UINT>(result);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
阅读您编辑的部分后,我认为您需要删除inline关键字。但我不确定。尝试这样做。:-)