2

Hello I wannted to build a helper class to initialize a stl valarray. What I would like is to do the following:

std::valarray<float> vec(3);
vlist_of<float>(vec)(2)(3)(5);

So I can just initialize the vectors at runtime using just one row command statement. For doing the following I have tryed the following structure:

template <typename T>
struct vlist_of {
    std::valarray<T>& data;
    int i;
    vlist_of(std::valarray<T>& _data):data(_data),i(0) {
        (*this)(data);
    }
    vlist_of& operator()(std::valarray<T>& data){return *this;}
    vlist_of& operator()(const T& t) {
       data [i]=t;
        i++;
        return *this;
    }
};

this structure works if I do the following :

vlist_of<float> tmp(vec);tmp(2)(3)(4);

Is it possible what I am asking ?

sehe
  • 374,641
  • 47
  • 450
  • 633
jamk
  • 836
  • 1
  • 10
  • 24
  • I don't understand what kind of answer you're looking for. By the way, what is `(*this)(data);` for? :v – user123 Mar 19 '13 at 10:49
  • @Magtheridon96 I think he's looking for `Boost Assign` style initialization for valarrays – sehe Mar 19 '13 at 11:13

1 Answers1

2

Yes. Make vlist_of a factory function:

template <typename T>
vlist_builder<T> vlist_of(std::valarray<T>& data)
{
    return vlist_builder<T>(data);
}

Now it works http://liveworkspace.org/code/48aszl$0.

I'd personally prefer uniform initialization:

/*const*/ std::valarray<float> prefer { 2, 3, 5 };

See full sample:

#include <valarray>
#include <vector>
#include <iostream>

template <typename T>
struct vlist_builder
{
    std::valarray<T>& data;
    int i;
    vlist_builder(std::valarray<T>& _data):data(_data),i(0) { }
    vlist_builder& operator()(const T& t)
    {
        data[i++]=t;
        return *this;
    }
};

template <typename T>
vlist_builder<T> vlist_of(std::valarray<T>& data)
{
    return vlist_builder<T>(data);
}

int main()
{
    std::valarray<float> vec(3);
    vlist_of<float>(vec)(2)(3)(5);

    for(auto f : vec)
        std::cout << f << "\n";

    // prefer uniform initialization:
    const std::valarray<float> prefer { 2, 3, 5 };
}
sehe
  • 374,641
  • 47
  • 450
  • 633