|
Boost : |
From: Christian Holmquist (c.holmquist_at_[hidden])
Date: 2007-05-10 06:56:15
Hello,
I've had much use of a small traits class for identifying types that matches
the STL Container concept (roughly) .
Two functions is made available, is_container<T> and
container_category_of<T>.
is_container simply evaluates to true_type or false_type,
container_category_of tries to categorize T with the following tags.
struct non_container_tag {};
struct container_tag {};
struct sequence_container_tag : public container_tag {};
struct associative_container_tag : public container_tag {};
struct hashed_container_tag : public associative_container_tag {};
template<class T, class Tag = container_tag>
struct is_container
It seems to work for STL containers, boost multi index, boost array etc..
haven't tried with ptr_containers yet but they should work, since the
implementation just looks for a couple of member types using
BOOST_MPL_HAS_XXX_TRAIT_DEF.
Writing stream operators for a container can be implemented like
template<class CharType, class CharTrait, class Container>
inline typename boost::enable_if<is_container<Container>,
basic_ostream<CharType, CharTrait>&>::type
operator <<(basic_ostream<CharType, CharTrait>& os, const Container& c)
{
if (!os.good() ) return os;
detail::write_container(os, c, d);
return os;
}
Writing a generic insert() could look something like
namespace detail
{
template<class Container, class T>
bool insert(Container& c, const T& t, sequence_container_tag)
{
c.push_back(t); return true;
}
template<class Container, class T>
bool insert(Container& c, const T& t, associative_container_tag)
{
return c.insert(t).second;
}
}
template<class Container, class T>
bool insert(Container& c, const T& t)
{
return detail::insert(c, t,
container_category_of<Container>::type());
}
Could this be of any use in boost?
/ Christian
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk