我在学习ratio
在 C++11 中。根据cplusplus.com和 Professional C++ 2nd 这本书(以下段落是其中的摘录)。
The numerator and denominator of a rational number are represented as compile time constants of type
std::intmax_t
. Because of the compile time nature of these rational numbers, using them might look a bit complicated and different than usual. You cannot define a ratio object the same way as you define normal objects, and you cannot call methods on it. You need to usetypedefs
.
这意味着我必须写
typedef ratio<1,3> one_third;
代替
ratio<1,3> one_third;
但是我发现这两种write ratio的方式都是可行的。我可以使用 .
访问 ratio 的成员或 ::
.
问题 1. cplusplus.com 和 Professional C++ 书错了吗?
以下代码段来自 cplusplus.com 示例。
typedef std::ratio<1,3> one_third;
typedef std::ratio<2,4> two_fourths;
typedef std::ratio_add<one_third,two_fourths> sum;
std::cout << sum::den << std::endl;
问题 2. 然而,我得到一个错误(使用 VS 2012)
error C2039: 'den' : is not a member of 'std::ratio_add<_R1,_R2>'
根据评论,使用typedef ratio_add<one_third, two_fourths>::type sum
更便携。
最佳答案
您不必使用 typedef
s,但正如书中所说,<ratio>
处理编译时数学,其中定义的元函数采用类型模板参数。
如果您不使用 typedef
您正在创建 std::ratio<1,3>
的实例名为 one_third
,不适合作为类型参数传递。在这种情况下,您需要使用 decltype
获得可以传递给 ratio_add
的适当类型
std::ratio<1,3> one_third;
std::ratio<2,4> two_fourths;
std::ratio_add<decltype(one_third), decltype(two_fourths)> sum;
std::cout << decltype(sum)::den << std::endl;
您看到的错误消息是因为 ratio_add
(和其他类似的元函数)实现是 not standard conforming on VS2012由于缺乏对别名模板的支持。如链接的错误报告中所述,解决方法是使用嵌套类型 type
.
typedef std::ratio_add<one_third,two_fourths>::type sum;
std::cout << sum::den << std::endl;
关于c++ - 为什么我可以在 C++ 中有一个比率对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005205/