vendredi 26 janvier 2018

Pass array through class constructor using C++ variadic templates

I would like to modernize a small mathematical library using new C++ paradigms (I have a C++17 compiler). In specific, I need to pass an array to a class through constructor.

This is the "classical" old way I used. It works

class Vector {
public:
    long double* elements;
public:
    Vector(int size, long double *array) {
        elements = new long double[size];
        for(int i = 0; i < size; i++) {
            elements[i] = array[i];
        }
    };

    virtual ~Vector() {
        delete []elements;
    }

};

int main() {
    long double array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    Vector vector = Vector(10, array);
    for (int i = 0; i < 10; i++) {
        std::cout << vector.elements[i] << std::endl;
    }

    return 0;
}

So, I tried to change Vector class with what I have understood about variadic templates and parameter pack. It doesn't work

class Vector {

public:
    long double* elements;
public:
    template<typename... Args>
    Vector(Args... args){
        constexpr int size = sizeof...(Args);
        elements = new long double[size]{args...};
    }
};

int main() {
    long double array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    Vector vector = Vector(array);
    for (int i = 0; i < 10; i++) {
        std::cout << vector.elements[i] << std::endl;
    }

    return 0;
}

The error returned by compiler is

error: cannot convert ‘long double*’ to ‘long double’ in initialization

    elements = new long double[size]{args...};

What am I doing wrong? Further, I'm wondering if it is possible to use a std::array instead of raw array, both either inside main method and in Vector class.

Aucun commentaire:

Enregistrer un commentaire