Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a strong typed integer in C++?

I would like a strong typed integer in C++ that compiles in Visual Studio 2010.

I need this type to act like an integer in some templates. In particular I need to be able to:

StrongInt x0(1);                  //construct it.
auto x1 = new StrongInt[100000];  //construct it without initialization
auto x2 = new StrongInt[10]();    //construct it with initialization 

I have seen things like:

class StrongInt
{ 
    int value;
public: 
    explicit StrongInt(int v) : value(v) {} 
    operator int () const { return value; } 
}; 

or

class StrongInt
{ 
    int value;
public: 
    StrongInt() : value(0) {} //fails 'construct it without initialization
    //StrongInt() {} //fails 'construct it with initialization
    explicit StrongInt(int v) : value(v) {} 
    operator int () const { return value; } 
}; 

Since these things are not POD's, they do not quite work.

like image 545
jyoung Avatar asked May 19 '12 14:05

jyoung


2 Answers

I just use an enumeration type when I want a strongly-typed integer.

enum StrongInt { _min = 0, _max = INT_MAX };

StrongInt x0 = StrongInt(1);
int i = x0;
like image 183
Jonathan Wakely Avatar answered Oct 21 '22 21:10

Jonathan Wakely


StrongInt x0(1);

Since these things are not POD's, they do not quite work.

These two things are incompatible: you can't have both constructor syntax and PODness. For a POD you'd need to use e.g. StrongInt x0 { 1 }; or StrongInt x0 = { 1 };, or even StrongInt x0({ 1 }); (that's a very round-about copy-initialization).

like image 1
Luc Danton Avatar answered Oct 21 '22 21:10

Luc Danton