vendredi 30 octobre 2015

Variadic template divider

I have the following little variadic template which is supposed to divide a series of numbers. As I understand it, this is a rough sketch of what would happen if I call divide(20, 2, 2) -> 20/ 2 / 2. Apparently it doesn't happen that well, as the answer I get is 20... It works fine when there are only two arguments.

#include <iostream>

template<class first_t>
auto divide(const first_t &first)
{
    return first;
}

template<class first_t, class... rest_t>
double divide(const first_t &first, const rest_t&... rest)
{
    return first / divide(rest...);
}

int main()
{
    std::cout << divide(20, 2, 2); //should print 5

    std::cin.get();
}

Aucun commentaire:

Enregistrer un commentaire