我有一些将枚举乘以整数的代码:

QuantLib::Date date2 = date + 12 * QuantLib::Months;

其中 QuantLib::Months 定义为:

enum TimeUnit { Days,
                Weeks,
                Months,
                Years
};

这给了我想要的结果 日期2 一年后 日期. 。但是,我无法理解这是如何实现的。

我原以为这不会编译。现在我觉得我到达了一个“十二个月”对象,然后由 QuantLib::Date '+' 运算符重载处理该对象,但我以前从未见过这种样式。

我有 C# 背景,所以可能有一些我在工作中不知道的事情。谁能解释一下发生了什么事吗?任何参考文档将不胜感激。

有帮助吗?

解决方案

以下其中一项在此生效:

  1. 在C++中,枚举类型可以隐式转换为整型。如果这种事发生在这里, date + 12 * QuantLib::Months 会是一样的 date + 12 * 2.

  2. 还可以重载枚举类型的运算符。在这种情况下,库可能定义了一个 operator* (int, QuantLib::TimeUnit) 它返回与 + 你正在做的。

我不知道 QuantLib, ,但我猜#2 就是正在发生的事情。 QuantLib 文档 证实了这一点(感谢@DaliborFrivaldsky 提供的链接)。

其他提示

By default, all enumerations are basically integer constants, and as all integer values you can use them in arithmetic expressions.

In your case the constant QuantLib::Months has the value 2, as enumerations starts from zero and are simply increased.


However, unless you have to make your own data/time functionality, I suggest you use the functionality available in the standard library <chrono> header (or Boost chrono if you don't have a C++11 capable compiler/library). It has all this functionality built-in.

Here is an example similar to your code

auto now = std::chrono::system_clock::now();  // The current time at the moment
auto then = now + std::chrono::hours(24 * 365);

The variable then will now be a time_point 24 * 365 hours in the future from now.

In your example you are using a so-called unscoped enumeration. Each enumeration has an underlying integral type (that is not necessary the type int There is no such a default rule for enumerations in C++). According to paragraph 4.5.3 of the C++ Standard (you asked some reference to documentation):

3 A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank (4.13) greater than the rank of long long in which all the values of the enumeration can be represented. If there are two such extended types, the signed one is chosen.

So in your example QuantLib::Months is converted to int because all values of the enumeration can be stored in an object of type int. Then usual arithmetic conversions are performed in the multiplicative operation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top