Ada subtype equivalent in C++

前端 未结 5 2098
悲&欢浪女
悲&欢浪女 2021-02-12 22:39

Does C++ offer something similar to Ada\'s subtype to narrow a type?

E.g.:

type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday,          


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 23:15

    Range checking has a cost. C++ has a zero cost policy for features: if you want the feature and you should pay a cost for it, you need to be explicit. That being said, mostly you can use some library or write your own.

    Also, what do you expect when someone tries to put Sunday to Working_Day? An exception (most likely)? To set it to Monday? To set it to Friday? Invalidate the object? Keep the same value and ignore that (bad idea)?

    As an example:

    #include 
    #include 
    using namespace std;
    
    enum class Weekday
    {
        Sunday= 0,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    };
    
    template 
    class RangedAccess
    {
        static_assert(max >= min, "Error min > max");
    private:
        T t;
    
        public:
        RangedAccess(const T& value= min)
        {
            *this= value;
        }
    
    
        RangedAccess& operator=(const T& newValue)
        {
            if (newValue > max || newValue < min) {
                throw string("Out of range");
            }
            t= newValue;
        }
    
        operator const T& () const
        { 
            return t; 
        }
    
        const T& get() const
        { 
            return t; 
        }
    };
    
    using Working_Day= RangedAccess;
    
    int main()
    {
        Working_Day workday;
    
        cout << static_cast(workday.get()) << endl; // Prints 1
        try {
            workday= Weekday::Tuesday;
            cout << static_cast(workday.get()) << endl; // Prints 2
            workday= Weekday::Sunday; // Tries to assign Sunday (0), throws
            cout << static_cast(workday.get()) << endl; // Never gets executed
    
        } catch (string s) {
            cout << "Exception " << s << endl; // Prints "Exception out of range"
        }
        cout << static_cast(workday.get()) << endl; // Prints 2, as the object remained on Tuesday
    }
    

    which outputs:

    1
    2
    Exception Out of range
    2
    

提交回复
热议问题