C++ 中的 Ada 子类型等价物

Ada subtype equivalent in C++

C++ 是否提供类似于 Ada 的 subtype 来缩小类型?

例如:

type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
subtype Working_Day is Weekday range Monday .. Friday;

不,不是天生的。

您所描述的可能最好表示为范围枚举,并附有一个单独的范围枚举,其中枚举的子集与 "parent" 范围枚举共享数值表示。

您可以进一步定义两者之间的一些转换,但如果不进行反思,就不可能真正做到优雅和直观,至少在没有硬编码和重复负载的情况下是不可能的,这反而违背了目的。

在编写 C++ 程序时,最好尝试完全放弃用其他语言编程所灌输的思维方式。

话虽如此,这实际上是一个非常好的功能创意,但我不会屏住呼吸!

解决方法:只使用枚举,并在需要的地方应用范围检查。

范围检查是有代价的。 C++ 对功能有一个零成本政策:如果你想要这个功能并且你应该为此付出代价,你需要明确。也就是说,大多数情况下您可以使用一些库或编写自己的库。

此外,当有人试图将 Sunday 放入 Working_Day 时,您会期待什么?一个例外(最有可能)?将其设置为 Monday?将其设置为 Friday?使对象无效?保持相同的值并忽略它(坏主意)?

举个例子:

#include <iostream>
#include <string>
using namespace std;

enum class Weekday
{
    Sunday= 0,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

template <class T, T min, T max>
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<Weekday, Weekday::Monday, Weekday::Friday>;

int main()
{
    Working_Day workday;

    cout << static_cast<int>(workday.get()) << endl; // Prints 1
    try {
        workday= Weekday::Tuesday;
        cout << static_cast<int>(workday.get()) << endl; // Prints 2
        workday= Weekday::Sunday; // Tries to assign Sunday (0), throws
        cout << static_cast<int>(workday.get()) << endl; // Never gets executed

    } catch (string s) {
        cout << "Exception " << s << endl; // Prints "Exception out of range"
    }
    cout << static_cast<int>(workday.get()) << endl; // Prints 2, as the object remained on Tuesday
}

输出:

1
2
Exception Out of range
2

使用 C++17 引入的 std::variant 可以(至少部分)实现您想要的。

struct Monday {};
struct Tuesday {};
/* ... etc. */
using WeekDay= std::variant<Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday>;

以下代码定义了 sub_variant_t,它根据提交的类型构造了一个新的 variant。例如。 using Working_Day= sub_variant_t<WeekDay,5>;Weekday.

中取出前五个元素
template<class T,size_t o,class S>
struct sub_variant_h;

template<class T,size_t o,size_t... I>
struct sub_variant_h<T,o,std::index_sequence<I...> >
{
    using type= std::variant<typename std::variant_alternative_t<(I+o),T>... >;
};

template<class T,size_t end, size_t beg=0>
struct sub_variant
{
    using type= typename sub_variant_h<T,beg,std::make_index_sequence<end-beg> >:type;
};

template<class T,size_t end, size_t beg=0>
using sub_variant_t = typename sub_variant<T,end,beg>::type;

如果要将值从 较小 类型 (Working_Day) 复制到 较大 类型 (Weekday) 您可以使用 WeekDay d3= var2var<WeekDay>( d1 );,其中 var2var 定义如下。

template<class toT, class... Types>
toT
var2var( std::variant<Types...> const & v )
{
    return std::visit([](auto&& arg) -> toT {return toT(arg);}, v);
}

看到这个livedemo

C++ 枚举和 Ada 枚举之间还有一些其他差异。 以下 Ada 代码演示了其中的一些差异。

with Ada.Text_IO; use Ada.Text_IO;

procedure Subtype_Example is
   type Days is (Monday, Tueday, Wednesday, Thursday, Friday, Saturday, Sunday);
   subtype Work_Days is Days range Monday..Friday;

begin
   Put_Line("Days of the week:");
   for D in Days'Range loop
      Put_Line(D'Image);
   end loop;
   New_Line;
   Put_Line("Days with classification:");
   for D in Days'Range loop
      Put(D'Image & " is a member of");
      if D in Work_Days then
         Put_Line(" Work_Days");
      else
         Put_Line(" a non-work day");
      end if;
   end loop;

end Subtype_Example;

这个程序的输出是:

Days of the week:
MONDAY
TUEDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Days with classification:
MONDAY is a member of Work_Days
TUEDAY is a member of Work_Days
WEDNESDAY is a member of Work_Days
THURSDAY is a member of Work_Days
FRIDAY is a member of Work_Days
SATURDAY is a member of a non-work day
SUNDAY is a member of a non-work day

子类型 Work_Days 与类型天有 is-a 关系。 Work_Days 的每个成员也是 Days 的成员。在此示例中,Work_Days 的有效值集是 Days.

的有效值集的子集

Ada 中的字符被定义为枚举。因此,为特殊用途定义 Character 类型的子类型很简单。以下示例从文件中读取文本并计算大写字母和小写字母出现的次数,忽略文件中的所有其他字符。

with Ada.Text_IO; use Ada.Text_IO;

procedure Count_Letters is
   subtype Upper_Case is Character range 'A'..'Z';
   subtype Lower_Case is Character range 'a'..'z';

   Uppers : array(Upper_Case) of Natural;
   Lowers : array(Lower_Case) of Natural;

   File_Name : String(1..1024);
   File_Id   : File_Type;
   Length    : Natural;
   Line      : String(1..100);
begin
   -- set the count arrays to zero
   Uppers := (Others => 0);
   Lowers := (Others => 0);

   Put("Enter the name of the file to read: ");
   Get_Line(Item => File_Name,
            Last => Length);

   -- Open the named file
   Open(File => File_Id,
        Mode => In_File,
        Name => File_Name(1..Length));

   -- Read the file one line at a time
   while not End_Of_File(File_Id) loop
      Get_Line(File => File_Id,
               Item => Line,
               Last => Length);
      -- Count the letters in the line
      for I in 1..Length loop
         if Line(I) in Upper_Case then
            Uppers(Line(I)) := Uppers(Line(I)) + 1;
         elsif Line(I) in Lower_Case then
            Lowers(Line(I)) := Lowers(Line(I)) + 1;
         end if;
      end loop;
   end loop;
   Close(File_Id);

   -- Print the counts of upper case letters
   for Letter in Uppers'Range loop
      Put_Line(Letter'Image & " =>" & Natural'Image(Uppers(Letter)));
   end loop;

   -- print the counts of lower case letters
   for Letter in Lowers'Range loop
      Put_Line(Letter'Image & " =>" & Natural'Image(Lowers(Letter)));
   end loop;
end Count_Letters;

定义了两个字符子类型。子类型 Upper_Case 包含从 'A' 到 'Z' 的字符值范围,而子类型 Lower_Case 包含从 'a' 到 [=33] 的字符值范围=].

创建了两个数组来计算阅读的字母数。数组 Uppers 由一组 Upper_Case 值索引。数组的每个元素都是 Natural 的实例,它是 Integer 的 pre-defined 子类型,仅包含 non-negative 值。数组 Lowers 由 Lower_Case 值集索引。 Lowers 的每个元素也是 Natural 的一个实例。

程序提示输入文件名,打开该文件,然后一次一行地读取文件。解析每一行中的字符。如果该字符是 Upper_Case 字符,则 Uppers 中由已解析字母索引的数组元素将递增。如果该字符是 Lower_Case 字符,则递增 Lowers 中由已解析字母索引的数组元素。

下面的输出是读取count_letters程序源文件的结果。

Enter the name of the file to read: count_letters.adb
'A' => 3
'B' => 0
'C' => 12
'D' => 0
'E' => 2
'F' => 13
'G' => 2
'H' => 0
'I' => 21
'J' => 0
'K' => 0
'L' => 36
'M' => 1
'N' => 9
'O' => 7
'P' => 4
'Q' => 0
'R' => 3
'S' => 2
'T' => 3
'U' => 9
'V' => 0
'W' => 0
'X' => 0
'Y' => 0
'Z' => 1
'a' => 51
'b' => 3
'c' => 8
'd' => 19
'e' => 146
'f' => 15
'g' => 16
'h' => 22
'i' => 50
'j' => 0
'k' => 0
'l' => 38
'm' => 13
'n' => 57
'o' => 48
'p' => 35
'q' => 0
'r' => 62
's' => 41
't' => 78
'u' => 19
'v' => 0
'w' => 12
'x' => 2
'y' => 6
'z' => 2

也许你可以用后置条件重载赋值

Ensures(result > 0 && result < 10);  

纯理论。没有尝试过自己。 不过大家怎么看呢?

但有趣的是,欣赏他们如何将 C++ 的每次升级都作为 高级功能 所有 Ada 程序员认为理所当然的东西。