Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c++ - How can the allowed range of an integer be restricted with compile time errors?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...