jeudi 29 septembre 2016

Template function with template arguments or typename

I am creating a template class that contains a vector of numerical data (can be int, float, double, etc). And it has one operation, which calls std::abs() on the data. Something like the following code.

#include <iostream>
#include <complex>
#include <vector>


template<typename T> class MyData
{
public:
   std::vector<T> data;
   MyData<T> my_abs() const;

};


template<typename T>
MyData<T> MyData<T>::my_abs() const
{
    MyData<T> output;
    output.data.reserve(data.size());
    typename std::vector<T>::const_iterator it;

    for (it = data.begin(); it != data.end(); it++)
    {
        output.data.push_back(std::abs(*it));
    }
    return output;
}


int main()
{
    MyData<double> A;
    A.data = std::vector<double>(10, -1.0);

    MyData<double> test = A.my_abs();

    for (auto el : test.data)
    {
        std::cout << el << std::endl;
    }
    return 0;
}

This works correctly for types such as int, float, double. I also want to be able to use this class for types such as std::complex<double>.

Looking around I found that I could use template template arguments:

template<template<typename> class T, typename U> class MyData
{
public:
   std::vector<T<U>> data;
   MyData<U> my_abs() const;

};


template<template<typename> class T, typename U>
MyData<U> MyData<T<U>>::my_abs() const
{
    MyData<U> output;
    output.data.reserve(data.size());
    typename std::vector<T<U>>::const_iterator it;

    for (it = data.begin(); it != data.end(); it++)
    {
        output.data.push_back(std::abs(*it));
    }
    return output;
}

The previous code does not work as my template class expects two arguments,

error: wrong number of template arguments (1, should be 2)
MyData<U> abs() const;
       ^

Ideally I would like something like the previous code. In which the my_abs() function returns the type of the template argument passed to my template. E.g if I use a std::complex<double> then my main function could look something like:

int main()
{
    MyData<std::complex<double>> A;
    A.data = std::vector<std::complex<double>>(10, std::complex<double>(-1.0, -1.0));

    MyData<double> test = A.my_abs();

    for (auto el : test.data)
    {
        std::cout << el << std::endl;
    }
    return 0;
}

I am not sure how this can be achieved (or if it is even possible using the same template class).

Aucun commentaire:

Enregistrer un commentaire