1

So I know that I cannot use a float as a template parameter:

template<float T>
float foo(const float param) { return param + T; }

I've heard that ratio can be used as an alternative. I'd like to do something like this:

template<ratio T>
float foo(const float param) { return param * T::num / static_cast<float>(T::den); }

Unfortunately ratio is not a complete type so that doesn't work at all. And ultimately I have to ask, why not just do:

template<int Num, int Denom>
float foo(const float param) { return param * Num / static_cast<float>(Denom); }

My preference would be to use a ratio because it more clearly represents what I'm trying to do. Could someone provide me a simple way to use ratio?

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
Jonathan Mee
  • 36,513
  • 20
  • 115
  • 270
  • 1
    @JesperJuhl Because the standard says so, and [the compiler believes it](http://rextester.com/CBF67843) – Igor Tandetnik Aug 11 '18 at 13:55
  • @JesperJuhl https://stackoverflow.com/a/11518757/2642059 I mean I assume that hasn't changed? I thought that was the point of `ratio`? – Jonathan Mee Aug 11 '18 at 13:55

1 Answers1

4

There's no type ratio. std::ratio is a class template. This template itself has numerator and denominator as template parameters.

If you want to use std::ratio it can be done like this:

template<class T>
float foo(const float param) {
    return param * T::num / static_cast<float>(T::den);
}

auto x = foo<std::ratio<4,7>>(42);
n. 1.8e9-where's-my-share m.
  • 102,958
  • 14
  • 123
  • 225