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.
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());
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With