C ++是否提供类似于Ada的subtype
来缩小类型的内容?
例如:
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
subtype Working_Day is Weekday range Monday .. Friday;
答案 0 :(得分:6)
不,不是本地的。
您所描述的内容最好用范围枚举表示,并带有一个单独的范围枚举和一个子集,这些枚举与“父级”范围枚举共享数字表示形式。
您可以进一步定义两者之间的某些转换,但是如果没有反思,就不可能使所有内容都优雅而直观,至少没有硬编码和重复大量工作会破坏此目的。
在编写C ++时,最好完全放弃使用其他语言进行编程所产生的思维方式。
话虽如此,尽管我不会屏住呼吸,但这实际上是一个很好的功能创意!
解决方法:仅使用枚举,然后在需要的地方应用范围检查。
答案 1 :(得分:4)
使用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 );
),则可以使用{{ 1}},其中var2var
的定义如下。
template<class toT, class... Types>
toT
var2var( std::variant<Types...> const & v )
{
return std::visit([](auto&& arg) -> toT {return toT(arg);}, v);
}
请参阅此livedemo。
答案 2 :(得分:4)
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
答案 3 :(得分:-1)
可能您可以使用后置条件使分配超载
Ensures(result > 0 && result < 10);
完全是理论上的。还没有尝试过自己。 但是你们怎么看?
但是很高兴看到C ++每次升级都是作为高级功能来推动Ada程序员视为理所当然的所有事情。
答案 4 :(得分:-3)
范围检查需要费用。 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