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.
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;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With