Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving different and incomparable types from int in C++

I know I cannot derive from an int and it is not even necessary, that was just one (non)solution that came to my mind for the problem below.

I have a pair (foo,bar) both of which are represented internally by an int but I want the typeof(foo) to be incomparable with the typeof(bar). This is mainly to prevent me from passing (foo,bar) to a function that expects (bar, foo). If I understand it correctly, typedef will not do this as it is only an alias. What would be the easiest way to do this. If I were to create two different classes for foo and bar it would be tedious to explicitly provide all the operators supported by int. I want to avoid that.

like image 433
san Avatar asked Aug 10 '11 11:08

san


Video Answer


1 Answers

As an alternative to writing it yourself, you can use BOOST_STRONG_TYPEDEF macro available in boost/strong_typedef.hpp header.

// macro used to implement a strong typedef.  strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation.  typedef does not create
// a new type.  BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.

So, e.g.

BOOST_STRONG_TYPEDEF(int, foo)
BOOST_STRONG_TYPEDEF(int, bar)
like image 135
Cat Plus Plus Avatar answered Sep 19 '22 16:09

Cat Plus Plus