• FEATURED

View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# a slick trick in c++

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

19 replies to this topic

### #1snk_kid  Members

Posted 05 August 2004 - 02:18 AM

here is a lil' slick trick brought together from discussions about pointer to data members taken to the almost extreme and cost you almost nout:

#include <cstddef>
#include <iostream>

template< typename T >
struct Vector4 {

typedef size_t size_type;

private:

typedef T Vector4<T>::* const vec[4];

static const vec v;

public:

T x, y, z, w;

Vector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0):
x(_x), y(_y), z(_z), w(_w) {}

const T& operator[](size_type i) const {
return this->*v[i];
}

T& operator[](size_type i) {
return this->*v[i];
}

};

template< typename T >
const typename Vector4<T>::vec Vector4<T>::v = { &Vector4<T>::x, &Vector4<T>::y, &Vector4<T>::z, &Vector4<T>::z };

template< typename T >
struct matrix4 {

typedef size_t size_type;

private:

typedef Vector4<T> matrix4::* const mat[4];

static const mat a;

public:

Vector4<T> i, j, k, l;

matrix4(const Vector4<T>& _i = Vector4<T>(),
const Vector4<T>& _j = Vector4<T>(),
const Vector4<T>& _k = Vector4<T>(),
const Vector4<T>& _l = Vector4<T>())
: i(_i), j(_j), k(_k), l(_l) {}

const Vector4<T>& operator[](size_type i) const {
return this->*a[i];
}

Vector4<T>& operator[](size_type i) {
return this->*a[i];
}
};

template< typename T >
const typename matrix4<T>::mat matrix4<T>::a = { &matrix4<T>::i, &matrix4<T>::j, &matrix4<T>::k, &matrix4<T>::l };

int main() {

matrix4<int> m;

m[0][0] = 10;

std::cout << "m[0][0]: " << m[0][0] << '\n';
std::cout << "m[0].x: " << m[0].x << '\n';
std::cout << "m.i.x: " << m.i.x << '\n';

return 0;

}



[Edited by - snk_kid on October 29, 2004 5:52:58 PM]

### #2dalleboy  Members

Posted 28 August 2004 - 08:54 AM

That is the nicest way of solving the problem (of indexing and naming variables at the same time) I've ever seen.

Edit: Spelling...

[Edited by - dalleboy on August 28, 2004 6:54:29 PM]

Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]

### #3Extrarius  Members

Posted 28 August 2004 - 09:04 AM

This was hashed out in a thread here not too long ago.

It was interesting because it was found that in VS.Net, the const on the array makes it optimize it perfectly and without it suboptimal code is generated.

### #4ldeej  Members

Posted 28 August 2004 - 10:08 AM

I find it a little bit too complex for something so simple.
Anonymous unions and anonymous structs solve the problem nicely:


template< typename T >
struct myVector4 {

typedef size_t size_type;

union
{
struct
{
T vec[4];
};

struct
{
T x, y, z ,w;
};

};

myVector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0):
x(_x), y(_y), z(_z), w(_w) {}

const T& operator[](size_type i) const {
return vec[i];
}

T& operator[](size_type i) {
return vec[i];
}
};

template< typename T >
struct myMatrix4 {

typedef size_t size_type;

union
{
struct
{
myVector4<T> comp[4];
};

struct
{
myVector4<T> i, j, k, l;
};
};

const myVector4<T>& operator[](size_type i) const {
return comp[i];
}

myVector4<T>& operator[](size_type i) {
return comp[i];
}
};


Edited by Fruny - Source tag and formatting.

### #5Fruny  Moderators

Posted 28 August 2004 - 10:18 AM

Quote:
 Original post by ldeejI find it a little bit too complex for something so simple.Anonymous unions and anonymous structs solve the problem nicely:

The only problem being that anonymous union members are not standard C++, while the solution above, as complex as you might think it to be, is standard C++.

The original discussion can be found here: Initializing array member objects in c++.

### #6Atm97fin  Members

Posted 28 August 2004 - 10:59 AM

Doesn't this produce the same results with less trouble?


template <typename T>
class vector3
{
T	vec[3];
public:
T	&x,&y,&z;
vector3() : x(vec[0]), y(vec[1]), z(vec[2])	{  };
T &operator [](int i) { return this->vec[i]; };
};

template <typename T>
class	matrix3
{
typedef vector3<T>	t_vector;

t_vector	vectors[3];
public:
t_vector	&i,&j,&k;

matrix3()	:	i(vectors[0]), j(vectors[1]), k(vectors[2]) { };

t_vector &operator[](int i) { return this->vectors[i]; };
};

vector3<float> vector;
matrix3<float> matrix;

vector.x = 1.0f;
vector[0] = 1.0f;

matrix.i.x = 1.0f;
matrix[0].x = 0.1f;
matrix[0][0] = 1.0f;



### #7Fruny  Moderators

Posted 28 August 2004 - 11:04 AM

Quote:
 Original post by Atm97finDoesn't this produce the same results with less trouble?*** Source Snippet Removed ***

Not quite, the references make your object non-assignable.

vector3<float> v1, v2;v1 = v2; // Boom

### #8hplus0603  Moderators

Posted 28 August 2004 - 11:05 AM

Atm97: no, that uses twice the amount of memory.

If VS.Net actually optimizes the const member function pointers, then I'm impressed, and it really will be cheap.

However, someone said that anonymous union names is not standard C++ -- that's false; the standard specifies that you don't have to name a union, and the naming of the inner elements then bind to the outer scope. So that's a pretty good solution.

Another solution is to realize that the struct layout rules still hold for classes as long as the classes don't have virtual member functions. Thus, this good-old solution is eqiuvalently cheap, and will not be expensive on less studly compilers (like GCC):


T & operator[]( size_t i ) {
assert( i < 4 );
return (&_x)[i];
}


Yes, this is guaranteed to work.

### #9Fruny  Moderators

Posted 28 August 2004 - 11:08 AM

Quote:
 Original post by hplus0603However, someone said that anonymous union names is not standard C++ -- that's false; the standard specifies that you don't have to name a union, and the naming of the inner elements then bind to the outer scope. So that's a pretty good solution.

You don't have to name the union, but you sure do have to name its members. This :
union{    struct { T vec[4]; };	    struct { T x, y, z ,w; };};

is non-standard, AFAIK.

### #10snk_kid  Members

Posted 28 August 2004 - 11:14 AM

wow it took 20 days for someone to respond lol

Quote:
 Original post by hplus0603If VS.Net actually optimizes the const member function pointers, then I'm impressed, and it really will be cheap.

its not a pointer to function member, its a pointer to data member.

EDIT: notice its a constant static class member aswell.

### #11Atm97fin  Members

Posted 28 August 2004 - 11:16 AM

Quote:
Original post by Fruny
Quote:
 Original post by Atm97fin Doesn't this produce the same results with less trouble? *** Source Snippet Removed ***

Not quite, the references make your object non-assignable.


vector3<float> v1, v2;
v1 = v2; // Boom




template <typename T>
class vector3
{
T	vec[3];
public:
T	&x,&y,&z;
vector3() : x(vec[0]), y(vec[1]), z(vec[2])	{  };
T &operator [](int i) { return this->vec[i]; };

vector3<T> &operator = (const vector3<T> &_vec) {	this->vec[0] = _vec.x;
this->vec[1] = _vec.y;
this->vec[2] = _vec.z;
return *this; };
};

vector3<float> v1,v2;

v1.x = 1.0f;
v2 = v1;



### #12Fruny  Moderators

Posted 28 August 2004 - 11:25 AM

Ok, fine. But your class is still bigger, and is not a POD-type. [wink]

### #13snk_kid  Members

Posted 28 August 2004 - 11:28 AM

Quote:
 Original post by Atm97finDoesn't this produce the same results with less trouble?

No it doesn't have look at the code closely, its a constant static/class member so only one instance of the member is created per class, the compiler can easily optimize the code.

where as your example creates three non-constant references per object/instance aswell as the array.

The link that Fruny gave to the older thread that gave me the idea for that, someone checked out the code generated by VS and posted there results check it out.

### #14ldeej  Members

Posted 28 August 2004 - 01:02 PM

AFAIK anonymous unions are standard C++.

The following should be valid across conforming compilers:

class Foo
{
union
{
//......
};
};

There is a non-standard extension I used on the code I presented:

class Foo
{
union
{
struct {}; // nameless nested struct is a MS extension
};
};

### #15Fruny  Moderators

Posted 28 August 2004 - 01:28 PM

Yup, that's what I said.

### #16snk_kid  Members

Posted 28 August 2004 - 02:03 PM

i tell what would be even more impressive if someone could figure out a way to either use this technique or combined approach with unions maybe so you could return a reference to either column vector or row vector from a matrix (not nessecarilly by overloading sub-script operator) without making copies of either one and it might lead to a quick tranpose operation?

### #17bobstevens  Members

Posted 28 August 2004 - 05:16 PM

Quote:
 Original post by FrunyOk, fine. But your class is still bigger, and is not a POD-type. [wink]

You really want a vector and/or matrix class that's a POD type? You didn't design RenderWare did you?

VectorDotProduct (VectorAdd (myVec, VectorSub (myVec2, myVec3)), myVec4); // ugh!

Edit: Ok you can overload operatators on POD types anyway I'm sure, but really this solves a problem that doesn't exist with a solution that's incomprehensible. Try slipping that past your boss and see if it comes back to bite you.

### #18Fruny  Moderators

Posted 28 August 2004 - 05:20 PM

Quote:
 Original post by bobstevensYou really want a vector and/or matrix class that's a POD type? You didn't design RenderWare did you?VectorDotProduct (VectorAdd (myVec, VectorSub (myVec2, myVec3)), myVec4); // ugh!

Being a POD-type doesn't preclude having member functions, but constructors (though granted snk_kid has one too), or reference members are right out.

Though, of course, there's nothing wrong with non-POD types. I'm just arguing for argumentation's sake ;)

### #19snk_kid  Members

Posted 28 August 2004 - 09:52 PM

Quote:
 Original post by bobstevens but really this solves a problem that doesn't exist

Or the problem isn't apparent to you, indeed it is very subtle and i should have probably explained at the beginning but it does solve a problem, actually it solves two problems.

1. if you use the union method using standard compliant c++ code you'll end up with something like this:


#include <cstddef>
#include <iostream>

template< typename T >
struct vector4 {

typedef size_t size_type;

struct vec {
T x, y, z ,w;
};

typedef typename vector4<T>::vec vec_type;

union {
T  v[4];
vec_type g;
};

const T& operator[](size_type i) const {
return v[i];
}

T& operator[](size_type i) {
return v[i];
}
};

template< typename T >
struct matrix4 {

typedef size_t size_type;

union {
vector4<T> vec[4];
vector4<T> i, j, k, l;
};

const vector4<T>& operator[](size_type i) const {
return vec[i];
}

vector4<T>& operator[](size_type i) {
return vec[i];
}
};

int main() {

matrix4<int> m;

m[0][0] = 10;

std::cout << "m[0][0]: "  <<  m[0][0] << '\n';
std::cout << "m[0].g.x: " <<  m[0].g.x  << '\n';
std::cout << "m.i.g.x: "  <<  m.i.g.x   << '\n';

return 0;

}



from that code notice this part of the code:


matrix4<int> m;

m[0][0] = 10;

std::cout << "m[0][0]: "  <<  m[0][0] << '\n';
std::cout << "m[0].g.x: " <<  m[0].g.x  << '\n';
std::cout << "m.i.g.x: "  <<  m.i.g.x   << '\n';


VS using pointer to data member version:


matrix4<int> m;

m[0][0] = 10;

std::cout << "m[0][0]: " << m[0][0] << '\n';
std::cout << "m[0].x: " << m[0].x << '\n';
std::cout << "m.i.x: " << m.i.x << '\n';


which one looks more natural to work with?

2. Fine fair enough so just say for a minute you started with the union method later on you decide that you wont to make some constructors in you main vector type using constructor initializer lists using the non-array members i.e. vec x, y, z, w, the only way you can do this is by giving the internal structure vec a constructor aswell but this also isn't standard compliant code because union members are not suppose to have constructors & destructors.

pointer to data members are not hacks, its completely legitimate standard compilant code & is probably safer than using public unions.

Quote:
 Original post by bobstevens that's incomprehensible.

you can easily make the "incomprehensible" part private not the case with unions so much [smile]

[Edited by - snk_kid on August 29, 2004 9:52:21 AM]

### #20monamimani  Members

Posted 14 October 2011 - 08:00 PM

Hi first, I am very sorry to wake a old thread but I am trying to implement this trick but slightly different and I can't make it work.

In the class of snk_kid, he has a static array and x,y,z,w members, what I what is to do the opposite. i want to make the x, y, z, w static member pointer and a member array to old the data.

Id it possible I can't mannage to make it work.

[source lang='cpp']template<typename ValueType, CoreFoundation::size_t Rows, CoreFoundation::size_t Cols>class Vector4{public: inline Vector4(ValueType x, ValueType y, ValueType z, ValueType w):x_(x), y_(y), z_(z), w_(w) { } inline ValueType operator()(CoreFoundation::size_t index) { return data_[index]; }; inline const ValueType& operator()(CoreFoundation::size_t index) const { return data_[index]; }; private: ValueType data_[Rows*Cols]; public:typedef ValueType Vector4< ValueType >::* const VectorElement; static VectorElement x_; };template<typename ValueType>typename Vector4<ValueType>::VectorElement Vector4<ValueType>::x_ = &(Vector4<ValueType>::data_[0]);[/source]

What doesn't work is the assignation of the static memeber.

anybody have a clue how to do this?

Thanks

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.