Skip to main content
GameDev.net gamedev.net
🔒 Locked

a slick trick in c++

Started by snk_kid Aug 5, 2004 at 8:18 AM 18 replies 19.1k views
Original Post
snk_kid
snk_kid
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;
   }

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

};

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;
   }

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

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]
Extrarius
Extrarius
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.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
ldeej
ldeej
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;  }  T& operator[](size_type i) {    return vec;  }};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;  }  myVector4<T>& operator[](size_type i) {    return comp;  }};


Edited by Fruny - Source tag and formatting.
Fruny
Fruny
Quote:
Original post by ldeej
I 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++.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Atm97fin
Atm97fin
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; };};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; };};        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;
EasyGL - easy to use graphics library.
Fruny
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
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
hplus0603
hplus0603
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);}


Yes, this is guaranteed to work.
enum Bool { True, False, FileNotFound };
Fruny
Fruny
Quote:
Original post by hplus0603
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.


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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
snk_kid
snk_kid
wow it took 20 days for someone to respond lol

Quote:
Original post by hplus0603
If 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.
Atm97fin
Atm97fin
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


Just add operator =
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; };	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;
EasyGL - easy to use graphics library.
Fruny
Fruny
Ok, fine. But your class is still bigger, and is not a POD-type. [wink]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
snk_kid
snk_kid
Quote:
Original post by Atm97fin
Doesn'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.
ldeej
ldeej
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
};
};
Fruny
Fruny
Yup, that's what I said.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
snk_kid
snk_kid
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?
bobstevens
bobstevens
Quote:
Original post by Fruny
Ok, 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.
Fruny
Fruny
Quote:
Original post by bobstevens
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!


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 ;)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
snk_kid
snk_kid
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;  }  T& operator[](size_type i) {    return v;  }};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;  }  vector4<T>& operator[](size_type i) {    return vec;  }};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]
monamimani
monamimani
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
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 Vector4::VectorElement Vector4::x_ = &(Vector4::data_[0]);
[/source]


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

anybody have a clue how to do this?

Thanks

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.