I'm trying to implement a wrapper class over unordered_map.
#include <iostream>
#include <unordered_map>
using namespace std;
template< class Key > class HashFn
{
public:
size_t operator() (Key & inKey);
};
template<> size_t HashFn< string >::operator()(string & inKey)
{
return std::hash<string>{}(inKey);
}
template< class Key, class Val, class Hash = HashFn< Key > > class unordered_map_wrapper
{
private:
unordered_map<Key, Val, Hash> * mTable;
public:
unordered_map_wrapper( );
bool insert( pair<Key, Val> & inPair );
};
template< class Key, class Val, class Hash > unordered_map_wrapper< Key, Val, Hash >::unordered_map_wrapper( )
{
mTable = new unordered_map< Key, Val, Hash >( );
}
template< class Key, class Val, class Hash > bool unordered_map_wrapper< Key, Val, Hash >::insert( pair<Key, Val> & inPair )
{
//internal implementation
return NULL;
}
int main() {
unordered_map_wrapper< string,unsigned > h();
h.insert(std::make_pair< string,unsigned >( "One", 1 ));
return 0;
}
Here hash Function is templated on templated class Key
.
The identifiers for unordered_map_wrapper templated class are Key
, Val
and Hash = HashFn< Key >
.
Here, we are using a template specialisation of the string as default and passing HashFn class
(template class) as the default argument.
When we are inserting it as a string, we are using an overloaded operator()
as specialisation.
If HashFn
class is not templated, instead if we are using only string
as a concrete implementation without templates, it works.
But when we are using the template, getting a compilation error:
test.cpp: In function ‘int main()’:
test.cpp:40:7: error: request for member ‘insert’ in ‘h’, which is of non-class type ‘unordered_map_wrapper<std::__cxx11::basic_string<char>, unsigned int>()’
h.insert(std::make_pair< string,unsigned >( "One", 1 ));
^~~~~~
It seems like we are not able to detect the template specialisation for the string in hashFn
class.
This issue appears only when h.insert()
is called or are we missing something.
Please suggest a way out. Thanks in advance!