dimanche 3 avril 2016

Applying a function over an arbitrary number of variadic arguments

This is a follow-up question to my previous one. I am building an Array class with basic vector math functionality. I want to define a function that lets a user map an arbitrary function over the entire array. I can already do this for predefined, binary functions (say, operator+= for in-place addition), but I am struggling to see how this could be done for an arbitrary number of inputs.

template<typename T, size_t ... Ns>
class Array
{
public:
    Array() { /* allocate memory of size product(Ns) * sizeof(T) */ }

    ~Array() { /* deallocate memory */ }

    inline Array<T, Ns...>& operator+=(const Array<T, Ns...> &rhs)                   
    {
        // simple case: predefined operation on exactly two Arrays
        T *p1 = data, *p2 = rhs.data;                                                
        while (p1 != data + size) { *p1 += *p2; p1++; p2++; }                                                                            
        return *this;                                                                
    }

    template<class ... Args>
    inline const Array<T, Ns...> map(T (*fn)(arg_type<Args>...), Args ... args)
    {
        // difficult case: arbitrary operations on a variable number of Arrays
    }

    private:
        T *data;
        size_t size;
}

// example usage
double f(double a, double b) { return a + b; }
Array<double,2> x, y, z;
x.map(f, y, z);

I would want something like this to loop over all elements in y and z, applying f to them, and storing them in x. I thought I could model it on my operator+= function, but I haven't yet found a parameter pack expansion that would let me do anything similar (and compile).

Aucun commentaire:

Enregistrer un commentaire