mosg
mosg

Reputation: 12381

HowTo create template of a container (e.x. std::map)?

So, I had a simple working code, for example

template <typename T, typename VALUE>
VALUE mapAt(T key)
{
    std::map<T, VALUE>::const_iterator item_i(MyMap.find(key))
                                      , end_i(MyMap.end());
    if (item_i == end_i)
    {
        throw std::exception("No such key!");
    }

    return (*item_i).second;
}

Question: is it possible to create a new template function without using std::map, but using different containers (e.x. std::map, std::multimap, ...), something like this:

template <class Container, typename T, typename VALUE>
VALUE mapAt(Container& MyMap, T key)
{
    Container<T, VALUE>::const_iterator item_i(MyMap.find(key))
                                       , end_i(MyMap.end());
    /* ... */
}

Problem: when i'm tring to use it, like:

std::map<int, char> my_map;
char ch = mapAt<std::map<int, char>(), int, char>(my_map, 123); // C2664 error

compiler gaves me an error:

main.cpp(119) : error C2664: 'mapAt' : cannot convert parameter 1 from 'std::map<_Kty,_Ty>' to 'std::map<_Kty,Ty> (_cdecl &)' 1>
with 1> [ 1>
_Kty=int, 1> _Ty=char 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Upvotes: 2

Views: 2924

Answers (1)

Asha
Asha

Reputation: 11232

You can write something like this:

template <class Container>
typename Container::mapped_type mapAt(Container& MyMap, typename const Container::key_type& key)
{
    typename Container::const_iterator iter = MyMap.find(key);
    return iter->second;
}

int main()
{
    std::map<int, char> my_map;
    char ch = mapAt(my_map, 123); 
}

Upvotes: 2

Related Questions