URL87
URL87

Reputation: 11012

Get value type of std::map which passed to template function

Having a template function -

template <class B>
B getValue (B& map) {
    // implementation ...       
}

To this function a pass a map , like -

map<string,double> doubleMap;
getValue (doubleMap);

So for example in this case, if I want to set the return value of the function to double according to doubleMap I should extract the value type of this map , also if I want to declare on a double (or any other type according to the passed map) I must have this ..

How can I get it ?

Upvotes: 2

Views: 5093

Answers (3)

BenS1
BenS1

Reputation: 105

Just in case it helps, here is an example of how I do it:

    template<typename MapType>
    static auto GetValueOrDefault(const MapType& map, const std::string& key, const typename MapType::mapped_type& defaultVal)
    {
        // Try to find the key
        auto iter = map.find(key);
        
        // If we didn't find it then return the default value
        if (iter == map.end())
            return defaultVal;

        // Return the value
        return iter->second;
    }

This is similar to arnoo's answer, but the one additional piece I had to do was add the keyword 'typename' before "MapType::mapped_type" in the function parameter list.

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49251

You can create a template that receives a container and exports its type arguments with a typedef: (an example for general tamplate argument type retrieval)

template <typename>
class GetTemplateArgs {};

template <typename ARG1, typename ARG2>
class GetTemplateArgs<std::map<ARG1,ARG2>>
{
  public:
    typedef ARG1 KEY;
    typedef ARG2 DATA;
};

template <class B>
typename GetTemplateArgs<B>::DATA getValue (B& map) {
    // implementation ...       
}

And of course you can then make it more specific for a map, so it will only recieve a map as the argument.

Upvotes: 2

arnoo
arnoo

Reputation: 511

std::map defines the member types key_type and mapped_type.

What you want is B::mapped_type, which will be double in your case.

Upvotes: 10

Related Questions