Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit specialization; 'std::hash<_Kty>' has already been instantiated

Tags:

c++

templates

first up, the code

"file.h"

namespace doge
{
    struct A
    {
        void func() = 0;
    };

    struct Aa : public A
    {
        std::string id;
        void func() override {}
    };

    template<T>
    struct Aaa: public Aa
    {
        T data;
        void func() override {}
    };

    class D
    {
    private:
        std::unordered_map<Aa,int> intMap;
        std::unordered_map<Aa,std::string> stringMap;
    };
}

namespace std
{
    template<> struct hash<doge::Aa>
    {
        std::size_t operator()(const doge::Aa & key)
        {
            return hash<string>()(key.id);
        }
    };
}

I'm getting the error in the title which seems to suggest multiple code for the hash has been generated. I get 2 of these in my error message, one for each unordered_map, can someone help me identify the problem. Thanks.

explicit specialization; 'std::hash<_Kty>' has already been instantiated
like image 650
demalegabi Avatar asked Oct 29 '25 08:10

demalegabi


1 Answers

Put the specialization of the hash before the unordered map.

When you first use the unordered map (of your type), the hash is already instantiated. It is an error to specialize it afterwards - this is both to avoid common mistakes and to make the compiler's life easier. You can 'break' the namespace definition safely to specialize and then continue adding to doge namespace.

like image 59
lorro Avatar answered Oct 31 '25 07:10

lorro