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
  • 50,140
  • 28
  • 121
  • 140
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 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. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Haha, I even linked to `std::ratio` in the question, and still got corrected. Anyways... is there anyway that I can do an `enable_if` or similar to enforce that `T` is of type `ratio`? – Jonathan Mee Aug 11 '18 at 14:24
  • 1
    You can, but why? Anything that has `num` and `den` as static members should be fine! – n. m. could be an AI Aug 11 '18 at 15:06