Vector access notation

18 07 2010

wish I could come up with a quirky and witty title for this post about vector math, but I just couldn’t.

I’ve managed to keep up with a post every 3-4 days, which makes me happy. I’ve looked over the posts and most of them are fairly verbose I would say, with very little code. Let’s change that, shall we.

I’ve been retouching my math library… Thinking of some better ways of doing things, and generally tidying up and trying to generalize/organize stuff into templates. May not be your cup of Tea, but hey, I drink Coffee right?

The first little thought that came to my mind was the fact I was using functions as accessors to the Vector underlying values array; now, I’m not particular about having these as functions but I know other people who get annoyed at typing:
vec1.x() = 10.0f

I admit, it does kind-of look weird [althought I got used to it]. So let’s change that. How? References. A reference is a constant synonym for some type [user or in-built]; it isn’t a pointer, it’s a synonym which can only be set to a type ONCE in its lifetime. That’s an important little point that took me a while to understand. So our new Vector class now looks like:
class Vector2
    float& x;
    float& y;
    inline Vector2(): x(m[0]), y(m[1]) {}
    float m[2];

And voila, that’s it, just type up:
vec1.x = 1.0f

And have fun!

That’ll be it for tonight, short and with some code; next on the agenda, defining traits for the math objects and generalizing the math expressions [functions] and parameters…

I fly a starship across the Universe divide; And when I reach the other side; I’ll find a place to rest my spirit if I can; Perhaps I may become a highwayman again




2 responses

19 07 2010

Correct me if I’m wrong, but when you use member references, the compiler can’t automatically create a copy assignment operator. And references can only be set in the constructor. How do you get around this?

20 07 2010

There’s no need for correction, but why would you try to get around it?
Writing my own functions rather than letting the compiler generate silent functions for me has always been my prefered mode of coding. And as for needing to initialize the references in the constructor, where else would you initialize them, you certainly don’t want to leave it up to the users of the class, you might end up with references which have nothing to do with your underlying data array.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: