dimanche 16 décembre 2018

Polynomial Multiplication using std::tuple using templates

Assuming I have a 2 tuples of representing coefficients of two polynomials, how do I compute there multiplication coefficients. I want to accomplish this using template.

mul_scalar multiplies value of tuple to a with the scalar. I am trying to use this function to extend to polynomial case. By iterating over one tuple and using mul_scalar

#include <tuple>
#include <utility> 
#include <iostream>

template<std::size_t I = 0, typename T, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
mul_scalar(const T& lhs, const std::tuple<Tp...> rhs ) // Unused arguments are given no names.
{ }

template<std::size_t I = 0, typename T, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
mul_scalar(const T& lhs, const std::tuple<Tp...> rhs)
{
    std::cout << (std::get<I>(rhs))*lhs << " ";
    mul_scalar<I + 1, T, Tp...>(lhs, rhs);
}

template <std::size_t I = 0, template <typename ...> class Tup1, template <typename ...> class Tup2, typename ...A, typename ...B>
inline typename std::enable_if<I < sizeof...(A), void>::type
mul_poly(const Tup1<A...>& lhs, const Tup2<B...> rhs)
{
    mul_scalar(std::get<I>(lhs), rhs);
    //mul_poly(lhs, rhs); with I = I + 1
    // However I can't figure how to give other template args
}

int main(){
    auto poly_1 = std::make_tuple(2,1);
    auto poly_2 = std::make_tuple(3,4,5);
    mul_scalar(3,poly_1);
    std::cout << "\n";

    // Expected output 6 8 10 3 4 5
    mul_poly(poly_1, poly_2);
}

Aucun commentaire:

Enregistrer un commentaire