gpt4 book ai didi

c++ - 我可以在 C++ 中创建强类型整数吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:23 26 4
gpt4 key购买 nike

我想要一个在 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,所以它们不太管用。

最佳答案

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

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

StrongInt x0 = StrongInt(1);
int i = x0;

关于c++ - 我可以在 C++ 中创建强类型整数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com