Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ratio<,> is constant, but what if I want to accept different ratios as an argument?

Perhaps an oxymoronic question: ratio<,> is, by definition, a compile-time constant.

However, I would like to construct durations with different ratios that can be specified by the caller of my method. I'm guessing I should be using something other than ratio and/or duration, then, but what?

I want to have, say, a class member that can be set at runtime, and I would like it to be of type ratio<,>. At some point in the code, where this member gets set/assigned, it would be assigned a constant ratio, but in my class, I don't want to specify what that ratio should be.

like image 775
Tatiana Racheva Avatar asked Jun 14 '18 06:06

Tatiana Racheva


2 Answers

Ok, you need a std::ratio which "can be specified by the caller". There are three different options:

  • The caller wants to set std::ratio template parameters during compile time. This is trivial, simply set the parameters, e.g. using quarter = std::ratio<1, 4>.
  • The caller wants to set std::ratio template parameters during runtime. This is not possible by definition, std::ratio is a compile-time constant. You will have to implement your own class for computing ratios during runtime or use some kind of library (I don't know of any, suggestions welcome!).
  • The caller merely wants to scale a std::duration (which is what you seem to use your std::ratio for). Then just multiply it with a number.
like image 161
andreee Avatar answered Oct 10 '22 03:10

andreee


The answer illustrates a common approach with C++ templates:

template<typename ratio_type>
returnvalue function_name(ratio_type const& r, other parameter...)
{ ... }

The point is, that the very type of the ratio contains information. Since types (often, but not always) are the parameters passed to templates, you forward those parameters via templates, too. Of course, this only shifts the problem to a different place, so at some point you will take the numerator and denominator from the ratio and use it as values.

BTW: Consider std::div (http://en.cppreference.com/w/cpp/numeric/math/div) as alternative.

like image 24
Ulrich Eckhardt Avatar answered Oct 10 '22 05:10

Ulrich Eckhardt