Unique Integer Types -- a useful C++ trick

  • Thread starter Christopher Brian Colohan
  • Start date
V

Victor Bazarov

Christopher said:
This has probably been done a zillion times before, but it is new to
me (and some of the folks I work with), and also quite useful.

Let me know if there are obvious improvements that I have missed. :)

http://www.colohan.com/docs/unique_integers.html

Preventing conversion-construction from anything is usually done using
the 'explicit' keyword. I think you might find looking into it useful.
It would be nice not to have the number stated as the template argument
when declaring typedefs. I am not sure it's possible, but I suspect
that it is.

In any case, interesting work.

V
 
J

Jonathan Turkanis

It would be nice not to have the number stated as the template argument
when declaring typedefs. I am not sure it's possible, but I suspect
that it is.

It can almost be done with CRTP:

struct set_num_t : unique_int<set_num_t> { };

The trouble is you lose the constructor taking an unsigned int and the private
constructor taking a bool. If you don't mind macros, you could do

#define UNIQUE_INT(name) \
struct name : unique_int<name> { \
private: name(bool); \
public: name(unsigned v = 0u) : unique_int<name>(v) { }\
}; \
/**/

UNIQUE_INT(set_num_t)
UNIQUE_INT(entry_num_t)
UNIQUE_INT(lru_entry_t)

Jonathan
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top