Template specialization in the header file

I understand that I have to put the code below (for template specialization) in a CPP file instead of a header file? Is there a way to do this in the header file?

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); } 

I would get an error if the above function is placed in error_code.h

error C2912: explicit specialization; 'UINT HashKey (const error_code &)' is not a specialization of the function template

Some source of links on why I need to do the template specialization described above. http://www.codeproject.com/KB/architecture/cmap_howto.aspx . The code below is selected from the article, and it is part of the MFC source code.

 // 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); } 
+4
source share
2 answers

I think you should do this in your header file.

 //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); } 

EDIT:

After reading the edited part, it seems to me that you need to remove the inline . Although I don’t . Try to do it. :-)

+2
source

I think all this means that you did not determine the version of the function template before specialization. I think the best way would be to put this in your own header file and the #include error.h and hashkey.h files at the beginning. Or you can just error.h include hashkey.h.

+2
source

Source: https://habr.com/ru/post/1334298/


All Articles