6 c++
我想创建一个整数值的类型,但限制范围.尝试使用超出允许范围的值创建此类型的实例应导致编译时错误.
我找到的示例允许在使用指定值之外的枚举值时触发编译时错误,但是没有允许限制范围的整数(没有名称)的示例.
这可能吗?
是的,但它很笨重:
// Defining as template but the main class can have the range hard-coded
template <int Min, int Max>
class limited_int {
private:
limited_int(int i) : value_(i) {}
int value_;
public:
template <int Val> // This needs to be a template for compile time errors
static limited_int make_limited() {
static_assert(Val >= Min && Val <= Max, "Bad! Bad value.");
// If you don't have static_assert upgrade your compiler or use:
//typedef char assert_in_range[Val >= Min && Val <= Max];
return Val;
}
int value() const { return value_; }
};
typedef limited_int<0, 9> digit;
int main(int argc, const char**)
{
// Error can't create directly (ctor is private)
//digit d0 = 5;
// OK
digit d1 = digit::make_limited<5>();
// Compilation error, out of range (can't create zero sized array)
//digit d2 = digit::make_limited<10>();
// Error, can't determine at compile time if argc is in range
//digit d3 = digit::make_limited<argc>();
}
Run Code Online (Sandbox Code Playgroud)
事情会更容易当的C++ 0x不与constexpr,static_assert和用户定义的文字.