C++ is the greatist and most terribleist!

Posted by HippieHunter Sat, 26 Apr 2008 07:56:00 GMT
template<typename T>
class MemberPointerContainer
{
  typedef int T::* MEMPTR;
public:
  MemberPointerContainer(MEMPTR element)
  {
    _element = element;
  }
   
  template<typename R>
  static MemberPointerContainer CreateMemberPointer(R T::* element)
  {
    return MemberPointerContainer(reinterpret_cast<MEMPTR>(element));
  }
 
  template<typename R>
  void Set(T& t, R value)
  {
    typedef R T::* MEMPTR_SPECIALIZED;
    t.*(reinterpret_cast<MEMPTR_SPECIALIZED>(_element)) = value;
  }
  MEMPTR _element;
};

class NetworkEntity
{
public:
  int field1;
  int field2;
  double field3;
};
#include<vector>
void main()
{
  std::vector< MemberPointerContainer<NetworkEntity> > vect;  
  vect.push_back(MemberPointerContainer<NetworkEntity>::CreateMemberPointer(&NetworkEntity::field1));
  vect.push_back(MemberPointerContainer<NetworkEntity>::CreateMemberPointer(&NetworkEntity::field2));  
  vect.push_back(MemberPointerContainer<NetworkEntity>::CreateMemberPointer(&NetworkEntity::field3));
  NetworkEntity net;
  vect[0].Set(net, 5);
}
the nice thing is that even with all this indirection going on getting and setting is just like calling a member via 'this' as far as the actual x86 instructions are concerned. Why might this bee cool and terrible? Well the basic readability of it defines the terribleness, that combined with the general idea that you can do literally anything with C++ is a reasonably straight forward yet often obscure manor. As for the greatness, well this bit-o-code is going to help me write persistence layers that dont suck to code for. Something along the lines of boost::serialize only light weightier and more specialized to dealing with my style of data structures.

Trackbacks

Use the following link to trackback from your own site:
http://www.archverse.com/typo/trackbacks?article_id=10

Comments

Leave a comment