Executing various arguments of a C ++ template

I am trying to create a BidirectionalMap class using (only) STL (no, boost is not an option). I have 99% percent of this working the way I want, but what I really can’t understand is how to make the template require two different types so that the [] operator can be correctly redefined. Sort of...

template < class KeyType, class ValueType > class BidirectionalMap { public: ... const ValueType& operator[](const KeyType& _k ) { return( m_keyMap[ _k ] ); } const KeyType& operator[](const ValueType& _v ) { return( m_valMap[ _v ] ); } private: std::map< KeyType > m_keyMap; std::map< ValueType > m_valueMap; }; main() { BidirectionalMap< Foo, Foo > fooMap; // won't work, ambiguous. BidirectionalMap< Foo, Bar > fooBarMap; // does work. } 

Thoughts? -R

+6
source share
2 answers

Just add the following partial specialization:

 template <typename T> class BidirectionalMap<T, T>; 

This will cause the compiler to create a template that is not defined (since the above is only declared) and a pledge if the user tries to pass the same type as both arguments to the template.

+15
source
Of course, the real question is: why such an arbitrary restriction?

I find it completely normal to have the same type as the key and value, so instead of providing an ambiguous operator overload, perhaps you could just provide two different methods?

 ValueType const& by_key(KeyType const&) const; KeyType const& by_value(ValueType const&) const; 

and run with it.

EDIT . Following @Georg Fritzsche's comment :)

Remember that one of the basic rules of overloading is that all overloads should have the same basic meaning.

+6
source

Source: https://habr.com/ru/post/890602/


All Articles