我可以在C++中创建一个强类型的整数吗?

jyo*_*ung 5 c++ visual-studio-2010 visual-c++ c++11

我想要一个在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 
Run Code Online (Sandbox Code Playgroud)

我见过这样的话:

class StrongInt
{ 
    int value;
public: 
    explicit StrongInt(int v) : value(v) {} 
    operator int () const { return value; } 
}; 
Run Code Online (Sandbox Code Playgroud)

要么

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; } 
}; 
Run Code Online (Sandbox Code Playgroud)

由于这些东西不是POD,它们不太有用.

Jon*_*ely 1

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

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

StrongInt x0 = StrongInt(1);
int i = x0;
Run Code Online (Sandbox Code Playgroud)

  • 隐式转换为任何整数类型的东西如何是强类型的?“枚举类”可能是有道理的...... (6认同)
  • OP 的示例也可以隐式转换为整数,而且它满足轻松(取消)初始化的要求。枚举类型不能相互转换,因此 enum StrongInt 和 enum Price 和 enum Quantity 都是不同的类型,不能相互转换,可用于重载和特殊化。使用枚举作为不同的整数类型是一项很棒的技术,尽管我总是惊讶它并没有更常用。 (2认同)