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