c++ - 为什么我可以在 C++ 中有一个比率对象

标签 c++ c++11 c++-chrono

我在学习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 use typedefs.

这意味着我必须写

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;

Live demo


您看到的错误消息是因为 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/

相关文章:

c++ - 我怎样才能插入一个集合和一个双端队列

c++ - QSerialPort 手动 RTS 开/关未同步调用

c++ - std::binding to a lambda: 编译错误

c++ chrono 以 HH :MM:SS when it needs to be in seconds. 毫秒为单位的时钟

c++ - 如何使用 chrono 确定运行时间

python - 使用 boost::python 将数据缓冲区放入 C++

c++ - opencv undefined 我的库有问题吗?

C++ 正则表达式 : Conditional replace

c++ - 抢占式多任务处理是否会干扰 C++11 发布-获取语义?

c++ - 什么时候将 std::common_type 与单个参数一起使用?