tags:

views:

155

answers:

3

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 ?

+3  A: 

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 ;)

Matthieu M.
Nice answer. To get it to compile, ';' are missing at the end of the structs and .front() doesn't work for everything
Tristram Gräbener
Oups, that what you get from answering a bit too fast: I've added the missing `;` and replaced `front` by a dereferenced `begin` :)
Matthieu M.
+3  A: 

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)

Johannes Schaub - litb
+1  A: 

Use specialization of template function:

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


template<typename K, typename V>
typename V first(std::map<K,V> & c)
{
    return c.begin()->second;
}
Dewfy