need to know the container category

D

Daniel Etzold

Hi,

I have something similar to this:

template< typename X, typename Y, typename T = std::map< X, Y > >
class A {
T _t;
};

T may be a sequence of pairs or an associative container, e.g.
T = std::map< X, Y > | std::list< std::pair< X, Y > > | ...

Now I want to implement the operator[] which returns Y& for a
given X. For associative containers it should use
_t.find( x ).second, for sequences it should use something
similar to this
for( T::it = _t.begin(); it != _t.end(); ++it )
if( it->first == x ) return it->second;


If the sequence would be a random access iterator I could use
iterator tags to call an appropriate overloaded method. But how
can I differ lists of pairs from maps or sequences of pairs from
associative containers in general?

Regards,
Daniel
 
H

Howard Hinnant

Daniel Etzold said:
Hi,

I have something similar to this:

template< typename X, typename Y, typename T = std::map< X, Y > >
class A {
T _t;
};

T may be a sequence of pairs or an associative container, e.g.
T = std::map< X, Y > | std::list< std::pair< X, Y > > | ...

Now I want to implement the operator[] which returns Y& for a
given X. For associative containers it should use
_t.find( x ).second, for sequences it should use something
similar to this
for( T::it = _t.begin(); it != _t.end(); ++it )
if( it->first == x ) return it->second;


If the sequence would be a random access iterator I could use
iterator tags to call an appropriate overloaded method. But how
can I differ lists of pairs from maps or sequences of pairs from
associative containers in general?

Regards,
Daniel

You could build a container traits type that is specialized for list,
map, and whatever else that spells out the capabilities of each
container (at compile time). Maybe something like:

template <class C> struct container_traits;

template <class T>
struct container_traits<std::list<T> >
{
static const bool has_find = false;
};

template <class T, class U>
struct container_traits<std::map<T, U> >
{
static const bool has_find = true;
};

Now you can use your container_traits to test and compile-time-branch to
the desired algorithm.

You might find container_traits already written for you at boost, but
I'm not positive. I know I've seen the idea discussed there though.

-Howard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top