Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing different C++ template arguments

Tags:

c++

templates

I'm try to create a BidirectionalMap class using (only) STL (no, boost is not an option.) I have 99% percent of it working the way that I want, but what I really can't figure out is how to force the template to require two different types so that operator[] can be properly overridden. Something like...

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

like image 536
Rob Harris Avatar asked Jun 15 '11 12:06

Rob Harris


1 Answers

Just add the following partial specialisation:

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

This will case the compiler to instantiate a template that isn’t defined (since the above is only declared) and bail if the user tries to pass the same type as both template arguments.

like image 188
Konrad Rudolph Avatar answered Sep 23 '22 15:09

Konrad Rudolph