Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 get std::map value_type from a variable

Is there a way to get the value_type from a variable of type std::map<K,V>

For example:

class Foo{
    private:
        std::map<int,double> myMap;
    public:
        void Bar(const std::map<int,double>& m)
        {
            using PairType = m::value_type; //How to enable something like this?
            std::vector<PairType> vec(m.size());
            read_ints_and_doubles(&vec, m.size()); //expects a void* (legacy lib I'm using)
        }
};

Obviously I know I can use std::map<int,double>::value_type, but I want this to be open for future changes.

I thought about using using MyMapType = std::map<int,double> and then simply use MyMapType everywhere, but I don't want to do that and it seems to me that there is a way to to get this information from the variable itself since this is all static information and I don't see why I can't access this info.

EDIT: This question is far different than the suggested dup: Declare variables that depend on unknown type in template functions since I don't try to declare any variable, and the type is known.

like image 930
ZivS Avatar asked Oct 10 '16 07:10

ZivS


2 Answers

You can use decltype (wandbox example):

using PairType = decltype(m)::value_type;

In the above snippet, decltype(m) evaluates to the type of m.


In your particular case, you may want to use std::remove_reference_t to remove the reference from the evaluated type - decltype does not automatically "decay" the evaluated type.

  • C++14 example:

    using PairType = decltype(m)::value_type;
    std::vector<std::remove_reference_t<PairType>> vec(m.size());
    
  • C++11 example (on wandbox):

    using PairType = decltype(m)::value_type;
    using RemoveRefPairType = typename std::remove_reference<PairType>::type;
    std::vector<RemoveRefPairType> vec(m.size());
    
like image 104
Vittorio Romeo Avatar answered Oct 01 '22 11:10

Vittorio Romeo


decltype will help you here, example:

int main()
{
    std::map<int, int> m;
    using mytype = decltype(m)::value_type;
    mytype r = {1, 5}; // std::pair<const int, int>
}
like image 24
Andreas DM Avatar answered Oct 01 '22 10:10

Andreas DM