Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if template parameter is a pair associative container?

Tags:

c++

templates

stl

Let's imagine I want to make a templated function that returns the first element of any stl container. The general way would be :

template<typename Container>
Container::value_type first(Container c){
    return *(c.begin());
}

This works for vectors, lists, deques, sets and so on.

However, for pair associative containers (std::map), if would like to have

return c.begin()->second;

How could I test (in the function or with template specialization) if I have an pair associative container ?

STL container seem to have no traits attached to it. Is it possible to check if it has a ::key_type ?

like image 338
Tristram Gräbener Avatar asked Feb 18 '10 14:02

Tristram Gräbener


2 Answers

You can do quite easily:

namespace result_of // pillaged from Boost ;)
{
  template <class Value>
  struct extract { typedef Value type; };

  template <class First, class Second>
  struct extract < std::pair<First,Second> > { typedef Second type; };
}

template <class Value>
Value extract(Value v) { return v; }

template <class First, class Second>
Second extract(std::pair<First,Second> pair) { return pair.second; }

template <class Container>
typename result_of::extract< typename Container::value_type >::type
first(const Container& c) { return extract(*c.begin()); }

I should note though, that I would probably add a test to see if the container is empty... Because if the container is empty, you're on for undefined behavior.

In movement:

int main(int argc, char* argv[])
{
  std::vector<int> vec(1, 42);
  std::map<int,int> m; m[0] = 43;
  std::cout << first(vec) << " " << first(m) << std::endl;
}

// outputs
// 42 43

Example shamelessly taken from litb ;)

like image 61
Matthieu M. Avatar answered Oct 25 '22 20:10

Matthieu M.


This one works:

template<typename T>
struct tovoid {
  typedef void type;
};

template<typename T, typename = void>
struct value_type {
  typedef typename T::value_type type;
  static type get(T const& t) {
    return *t.begin();
  }
};

template<typename T>
struct value_type<T, typename tovoid<typename T::mapped_type>::type> {
  typedef typename T::mapped_type type;
  static type get(T const& t) {
    return t.begin()->second;
  }
};

template<typename Container>
typename value_type<Container>::type first(Container const& c){
    return value_type<Container>::get(c);
}

int main() {
  std::map<int, int> m; m[0] = 42; std::cout << first(m);
  std::vector<int> a(1, 43); std::cout << first(a);
}

(outputs 4243)

like image 3
Johannes Schaub - litb Avatar answered Oct 25 '22 21:10

Johannes Schaub - litb