6

我想要在 Visual Studio 2010 中编译的 C++ 中的强类型整数。

我需要这种类型在某些模板中充当整数。特别是我需要能够:

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

我见过这样的事情:

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

或者

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; } 
}; 

由于这些东西不是 POD,所以它们不太有效。

4

2 回答 2

1

当我想要一个强类型整数时,我只使用枚举类型。

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

StrongInt x0 = StrongInt(1);
int i = x0;
于 2012-05-19T18:06:08.110 回答
1
StrongInt x0(1);

由于这些东西不是 POD,所以它们不太有效。

这两件事是不兼容的:你不能同时拥有构造函数语法和 POD。对于 POD,您需要使用例如StrongInt x0 { 1 };or StrongInt x0 = { 1 };,甚至StrongInt x0({ 1 });(这是一个非常迂回的复制初始化)。

于 2012-05-19T15:09:15.913 回答