I've been trying to use Variadic Tuples on Generic Templates and Structs. The idea is to obtain the max and sum of a variadic tuple. So far I was able to obtain the required results but had to use Global static variables. I've posted the code below of the implementation.
#include <iomanip>
#include <complex>
#include <cmath>
#include <tuple>
#include <string>
#include <iostream>
using namespace std;
using namespace std::complex_literals;
template<typename T>
static T max;
template<typename T>
static T sum;
template<typename T>
static T average;
template <typename T, typename Tuple, std::size_t N>
struct Calculator
{
static void maximum(const Tuple& pack)
{
Calculator<T, Tuple, N - 1>::maximum(pack);
T packValue = get<N - 1>(pack);
if (packValue > max<T>)
{
//T max = get<0>(pack);
//Try the above instead of the below code to calculate max
max<T> = get<N - 1>(pack);
}
}
static void summation(const Tuple& pack)
{
Calculator<T, Tuple, N - 1>::summation(pack);
T packValue = get<N - 1>(pack);
sum<T> += packValue;
}
static void averager(const Tuple& pack)
{
average<T> = sum<T> / N;
}
};
template<typename T, typename Tuple>
struct Calculator<T, Tuple, 1>
{
static void maximum(const Tuple& pack)
{
//T max = get<0>(pack);
//Try the above instead of the below code to calculate max
max<T> = get<0>(pack);
}
static void summation(const Tuple& pack)
{
sum<T> = get<0>(pack);
}
};
int main()
{
tuple<double, double, double, double, double, double, double> t1 = make_tuple(16565.256, 45.539, 0.25, 1000.25, 1.25036, 35.66, 210.20);
Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::maximum(t1);
cout << "Maximum is: " << max<double> << endl;
Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::summation(t1);
cout << "Total Sum is: " << sum<double> << endl;
Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::averager(t1);
cout << "Average is: " << average<double> << endl;
std::complex<int> c2(22, 3);
std::complex<int> ci(15, 41);
tuple<std::complex<int>, std::complex<int> > ct1 = make_tuple(ci, c2);
Calculator< std::complex<int>, tuple<std::complex<int>, std::complex<int> >, 2>::summation(ct1);
cout << "Summation of complex numbers is: " << sum<std::complex<int>> << endl;
}
My question, is it possible to implement a version that doesn't use Global static variables to hold the values of sum and max but an alternate implementation using Variadic Templates and Structs if possible?
Aucun commentaire:
Enregistrer un commentaire