0

I have a function that rounds a value according to a policy

double round(double f, Policy p);

What I want to do now is to build a version of this that can be applied only to a container of doubles (there's no point in having a container of any other type due to the way the rounding works).

template <class Iterable>
Iterable<double> round(
    Iterable<double> y, Policy p){
    for (auto&& e : y){
        e = round(e, p);
    }
    return y;
}

I know my template syntax is not correct, but what should it be?

  • 1
    Here is your answer, I think, https://stackoverflow.com/questions/213761/what-are-some-uses-of-template-template-parameters – luk32 Nov 23 '18 at 11:51
  • You don't have to specify anything about `y`, just write `for (double & d : y)` – Caleth Nov 23 '18 at 12:30

1 Answers1

3

You need to use template-template parameters:

#include <vector>

template <template <typename...> class Container, typename T>
auto round(Container<T> y){
    for (auto&& e : y){
        // ...
    }
    return y;
}

int main()
{
    std::vector<double> vec = {1.1, 2.2};
    std::vector<double> rounded = round(vec);
}

live on coliru

m.s.
  • 16,063
  • 7
  • 53
  • 88
  • the OP specifically asked to restrict the use to only containers of `double`. Your code has no problem to compile for `std::vector`. – bolov Nov 23 '18 at 11:59
  • It is nonetheless an elegant solution. The OP could always static_assert on `T` if they insisted. – Bathsheba Nov 23 '18 at 12:01