繁体   English   中英

在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;

不,不是本地的。

您描述的内容可能最好表示为作用域枚举,并附带一个单独的作用域枚举,其枚举子集与“父”作用域枚举共享数字表示。

你可以进一步定义两者之间的一些转换,但是如果没有反射,它就不可能使它变得优雅和直观,至少不是没有硬编码和复制那些相当失败的东西。

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

话虽这么说,这实际上是一个很好的功能想法,虽然我不会屏住呼吸!

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

您想要的(至少部分地)可以使用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与类型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;

定义了两个Character的子类型。 子类型Upper_Case包含从“A”到“Z”的字符值范围,而子类型Lower_Case包含从“a”到“z”的字符值范围。

创建两个数组用于计算读取的字母数。 数组Uppers由一组Upper_Case值索引。 数组的每个元素都是Natural的实例,它是Integer的预定义子类型,仅包含非负值。 数组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程序员认为理所当然的高级功能

范围检查有成本。 C ++对于功能有一个零成本策略:如果你想要这个功能,你应该为它付出代价,你需要明确。 话虽这么说,大多数情况下你可以使用一些库或自己编写。

另外,当有人试图把Sunday送到Working_Day时你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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM