Is there any way to trick the compiler into allowing template specializations in the header file?
Normally when you write a template class and have a specialization of a function in that class, you need to put the specialization in the .cpp file since it is a concrete definition (rather than a template definition). If you only have one tiny function to specialize though this is a l开发者_Python百科ittle annoying and sometimes you may forget to look in that .cpp file for that one last definition which can cause confusion.
In a situation like this it would be nice to include that one specialization in the header file with the rest of the template definition. Is there any trick that would allow this to be achieved?
Use the inline
keyword:
template <unsigned N>
unsigned get_const()
{
return N;
}
template <>
inline unsigned get_const<42>()
{
throw "meaning of life";
}
The keyword indicates that multiple definitions should assumed to be the same, and therefore not an error. (This is orthogonal to static
, which keeps repeat definitions in their own translation unit.)
Note that this works with all functions, not just templates or specializations.
You can surround the specializations into the empty namespace
, but this may cause them to be defined in a different namespace. Then, you can create aliases in the empty namespace that are typedef
s to those specializations.
精彩评论