Why do I have a relationship object in C ++

I study the ratio in C ++ 11. According to cplusplus.com , and the book is Professional C ++ 2nd (the next paragraph is an excerpt from it).

The numerator and denominator of a rational number are represented as constants of compilation time of the type std::intmax_t . Due to the compilation of the temporary nature of these rational numbers, their use may look a little complicated and different from the usual. You cannot define a relationship object in the same way you define normal objects, and you cannot call methods on a topic. You need to use typedefs .

That means I have to write

 typedef ratio<1,3> one_third; 

instead

 ratio<1,3> one_third; 

But I find that these two ways of recording ratio work. And I can access the members of the relationship using either . , or :: .

Question 1. Are the books cplusplus.com and Professional C ++ wrong?

The following snippet is from cplusplus.com example.

 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; 

Question 2. However, I got an error (since VS 2012)

 error C2039: 'den' : is not a member of 'std::ratio_add<_R1,_R2>' 

According to the comments, using typedef ratio_add<one_third, two_fourths>::type sum more portable.

+6
source share
1 answer

You do not need to use typedef s, but as the book says, <ratio> deals with compile-time maths, and the meta-functions defined in it take arguments of a type template.

If you are not using typedef , you create an instance of std::ratio<1,3> named one_third , which is not suitable for passing as an argument of type. In this case, you will need to use decltype to go to the corresponding type, which can be passed to 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


The error message you see is due to the fact that the implementation of ratio_add (and other similar meta-functions) does not comply with the VS2012 standard due to the lack of support for alias patterns. As described in the linked error report, a workaround is to use the nested type type .

 typedef std::ratio_add<one_third,two_fourths>::type sum; std::cout << sum::den << std::endl; 
+12
source

Source: https://habr.com/ru/post/972995/


All Articles