I'm trying to compile this piece of code but with Gcc15 and Clang21 it doesn't compile. It does compile with gcc 14 and Clang20.
I want to create a std::unordered_map and use a class with explicit constructor as key.
#include <unordered_map>
#include <iostream>
class Key{
public:
explicit Key(){}
explicit Key(unsigned int x):_k{x}
{}
size_t operator()(const Key& p) const {
return p._k;
}
private:
unsigned int _k;
};
int main(int argc, char** argv) {
std::unordered_map<Key, int, Key> m;
return 0;
}
The problem is related to the keywork explicit. Removing the explicit keyword make the code compile.
This is the error reported by gcc15
In file included from /cefs/ac/ac576b8994a054d93ddc62cc_gcc-trunk-20251014/include/c++/16.0.0/bits/hashtable.h:37,
from /cefs/ac/ac576b8994a054d93ddc62cc_gcc-trunk-20251014/include/c++/16.0.0/bits/unordered_map.h:33,
from /cefs/ac/ac576b8994a054d93ddc62cc_gcc-trunk-20251014/include/c++/16.0.0/unordered_map:43,
from <source>:1:
/cefs/ac/ac576b8994a054d93ddc62cc_gcc-trunk-20251014/include/c++/16.0.0/bits/hashtable_policy.h: In instantiation of 'constexpr std::__detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Hash, _RangeHash, _Unused, <anonymous> >::_Hash_code_base() [with _Key = Key; _Value = std::pair<const Key, int>; _ExtractKey = std::__detail::_Select1st; _Hash = Key; _RangeHash = std::__detail::_Mod_range_hashing; _Unused = std::__detail::_Default_ranged_hash; bool <anonymous> = true]':
recursively required from 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = Key; _Tp = int; _Hash = Key; _Pred = std::equal_to<Key>; _Alloc = std::allocator<std::pair<const Key, int> >]'
<source>:19:37:
19 | std::unordered_map<Key, int, Key> m;
| ^
required from here
<source>:19:37:
/cefs/ac/ac576b8994a054d93ddc62cc_gcc-trunk-20251014/include/c++/16.0.0/bits/hashtable_policy.h:1056:62: error: converting to 'Key' from initializer list would use explicit constructor 'Key::Key()'
1056 | [[__no_unique_address__]] _Hashtable_ebo_helper<_Hash> _M_hash{};
| ^~~~~~~
<source>:6:14: note: 'Key::Key()' declared here
6 | explicit Key(){}
|
How can i get it to compile with the newer compilers?
Keyas a hash functor. ButKeyis not a functor, since it is not default constructible