• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
snk_kid

a slick trick in c++

19 posts in this topic

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]
1

Share this post


Link to post
Share on other sites
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]
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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++.
0

Share this post


Link to post
Share on other sites
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;


0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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[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;


0

Share this post


Link to post
Share on other sites
Ok, fine. But your class is still bigger, and is not a POD-type. [wink]
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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
};
};
0

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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 ;)
0

Share this post


Link to post
Share on other sites
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]
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0