mardi 26 janvier 2016

C++ Define an RValue property in a class

I have a vector with value:

obj={1.0,2.0,3.0, 4.0,5.0,6.0 ,7.0,8.0,9.0,10.0}

and I need to change the values of the sub-vector from index 3 to 6;

obj={1.0,2.0,3.0, -4.0,-5.0,-6.0 ,7.0,8.0,9.0,10.0}

The following code works:

#include <armadillo>
#include <iostream>

using namespace std;

typedef arma::vec::fixed<10> x_vec;

class B
{
public:
    x_vec data;

    B(x_vec init) :
        data(init)
    {
    }

    inline decltype(data.subvec(3,5)) myvec()
    {
        return data.subvec(3,5);
    }
};

int main()
{
    B obj({1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0});
    cout<<"sizeof obj.data: "<<sizeof(obj.data)<<endl;
    cout<<"sizeof obj: "<<sizeof(obj)<<endl;
    cout<<"value of obj:"<<endl;
    obj.data.print();

    obj.myvec()=-obj.myvec();

    cout<<"value of obj:"<<endl;
    obj.data.print();

    return 0;
}

Result

sizeof obj.data: 192
sizeof obj: 192
value of obj:
    1.0000
    2.0000
    3.0000
    4.0000
    5.0000
    6.0000
    7.0000
    8.0000
    9.0000
   10.0000
value of obj:
    1.0000
    2.0000
    3.0000
   -4.0000
   -5.0000
   -6.0000
    7.0000
    8.0000
    9.0000
   10.0000

However, how to make it work without parenthesis on the property?

I mean using

obj.myvec=-obj.myvec;

instead of

obj.myvec()=-obj.myvec();

I don't want to increase the size of my obj too.

Aucun commentaire:

Enregistrer un commentaire