C++是否提供类似于Ada的subtype
来缩小类型范围的功能?
例如:
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
subtype Working_Day is Weekday range Monday .. Friday;
C++是否提供类似于Ada的subtype
来缩小类型范围的功能?
例如:
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
subtype Working_Day is Weekday range Monday .. Friday;
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;
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
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;
template<class toT, class... Types>
toT
var2var( std::variant<Types...> const & v )
{
return std::visit([](auto&& arg) -> toT {return toT(arg);}, v);
}
你可能可以使用后置条件来重载赋值操作符
Ensures(result > 0 && result < 10);
范围检查是有成本的。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
short enum class : Weekday { Weekday::Monday, Weekday::Tuesday };
;) - Lightness Races in Orbit