如何限制整数的允许范围与编译时错误? [英] How can the allowed range of an integer be restricted with compile time errors?

查看:121
本文介绍了如何限制整数的允许范围与编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类型,它是一个整数值,但限制范围。
尝试创建一个值超出允许范围的这种类型的实例将导致编译时错误。



我发现了允许编译时错误的例子在使用指定值以外的枚举值时触发,但没有允许


解决方案

是的,但很笨重:

  //定义为模板,但主类可以有范围硬编码
template< int Min,int Max>
class limited_int {
private:
restricted_int(int i):value(i){}
public:
template< int Val> //这需要是编译时错误的模板
static limited_int make_limited(){
static_assert(Val> = Min&& Val< = Max,Bad!Bad value。 );
//如果你没有static_assert升级你的编译器或使用:
// typedef char assert_in_range [Val> = Min&& Val = Max];
return Val;
}
int value;
};

typedef limited_int< 0,9>数字;
int main(int argc,const char **)
{

//错误不能直接创建(ctor是私有的)
//数字d0 = 5;

// OK
digit d1 = digit :: make_limited< 5>();

//编译错误,超出范围(不能创建零大小的数组)
//数字d2 = digit :: make_limited< 10>();

//错误,如果argc在范围内,不能在编译时确定
//数字d3 = digit :: make_limited< argc>();
}

C ++ 0x 出现在 constexpr static_assert 用户定义文字


I would like to create a type that is an integer value, but with a restricted range. Attempting to create an instance of this type with a value outside the allowable range should cause a compile time error.

I have found examples that allow compile time errors to be triggered when an enumeration value outside those specified is used, but none that allow a restricted range of integers (without names).

Is this possible?

解决方案

Yes but it's clunky:

// 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) {}
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;
};

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

Things will be much easier when C++0x is out with constexpr, static_assert and user defined literals.

这篇关于如何限制整数的允许范围与编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆