Can I specialize forward declared template? For example:
template <typename T> class A;
template <>
class A<char> {
char a[1000];
};
int main()
{
[[maybe_unused]] A<char> a;
return 0;
}
What do I want to achieve?
As we know, we have to specialize std::hash
to use it with some hash-table-based types. Standard std::hash
specialization requires to include <functional>
in the header file and then specialize it. I use this header file in many places, and the compilation time of <functional>
is pretty big. So I want to move my specialization to source (cpp) file.
my_type.hpp:
class my_type {/*...*/};
namespace std {
template <typename T>
struct hash;
template <>
struct hash<my_type>
{
size_t operator()(my_type m) const;
};
} // namespace std
my_type.cpp:
#include "my_type.hpp"
#include <functional>
namespace std {
size_t std::hash<my_type>::operator()(my_type v) const
{
return std::hash<decltype(v.value())>{}(v.value());
}
} // namespace std
This solution works, but is it legal in terms of ISO standard?
EDIT/NOTE: It doesn't work with libc++ (clang std implementation), because it defines std::hash
as std::__1::hash
, where __1
is inline namespace. This partially answers the question.