a slick trick in c++

Started by
18 comments, last by monamimani 12 years, 6 months ago
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]
Advertisement
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]
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
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.
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
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.
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
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 };
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
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.

This topic is closed to new replies.

Advertisement