# std::valarray and classes

## Recommended Posts

Hi, Has anyone used valarrays with classes and overloaded operators before in vs2005? I'm attempting to write a nicer version of some vertex blending code I wrote long ago using a valarray of vertex classes. I take one slice of the previous frame's vertices, another of the next frames and add them together with weighting.
//Setup a slice to extract previous frame's vertices from vertex valarray
slice PreviousFrameSlice(NumVerticesPerFrame*StartFrame,1,NumVerticesPerFrame);
//Setup a slice to extract next frame's vertices from vertex valarray
slice NextFrameSlice(NumVerticesPerFrame*(StartFrame+1),1,NumVerticesPerFrame);
//Calculate vertex blending amount
Amount=(Frame+(float)SegmentStartFrame)-(float)StartFrame;
//Inbetween
InBetweenedVertices=(this->Vertices[PreviousFrameSlice]*(1.0f-Amount))+
(this->Vertices[NextFrameSlice]*Amount);


The class has the operators overloaded that I would have thought it needed:
//Vertex structure for use in models with only 1 set of texture coords
class ModelVertex
{
public:
float x;
float y;
float z;
float TextureCoords[2];
float Normals[3];

ModelVertex operator*(float K)
{
ModelVertex NV;

NV.x=this->x*K;
NV.y=this->y*K;
NV.z=this->z*K;

return NV;
}
ModelVertex operator*(ModelVertex V)
{
ModelVertex NV;

NV.x=V.x+this->x;
NV.y=V.y+this->y;
NV.z=V.z+this->z;

return NV;
}
};


But the code just won't compile, vc2005 comes up with:
Quote:
 .\src\CModel.cpp(128) : error C2678: binary '*' : no operator found which takes a left-hand operand of type 'std::slice_array<_Ty>' (or there is no acceptable conversion) with [ _Ty=ModelVertex ]
Has anyone ever used valarrays with classes? It would seem to go against the whole stl/c++ philosophy if what you could do with base types in a valarray can't be done with objects.. Cheers Jamie

##### Share on other sites
Vertices[PreviousFrameSlice] gives a slice_array, whose members don't include an operator*. But valarray does have operator* so you could try something like
InBetweenedVertices = valarray<ModelVertex>(this->Vertices[PreviousFrameSlice]) * (1.0f-Amount) + valarray<ModelVertex>(this->Vertices[NextFrameSlice]) * Amount;
but the problem is that it only has operator* where both sides are of similar type (i.e. where one side is T and the other is valarray<T>, or both are valarray<T>) - so I think you'd have to declare something new like
template <typename T, typename S> inline valarray<T> operator*(const valarray<T>& a, const S& b) {    valarray<T> r(a.size());    for (size_t i = 0; i < r.size(); ++i)        r[i] = a[i] * b;    return r;}
to make it work.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628306
• Total Posts
2981941

• 9
• 11
• 11
• 11
• 10