[ create a new paste ] login | about

Link: http://codepad.org/WyaACM7O    [ raw code | output | fork ]

joel_f - C++, pasted on Jun 15:
#include <iostream>


template<class T, int Padding>
struct padded
{
  static const 
  size_t buffer_size = (sizeof(T)<=Padding) ? Padding : Padding-sizeof(T);

  padded()             { new(&buffer[0]) T;      }

  // Use BOOST_PP to generate more of this
  template<class U> 
  padded(U const& val) { new(&buffer[0]) T(val); }

  T*       data()       { return (T*)(&buffer[0]); }
  T* const data() const { return (T*)(&buffer[0]); }

  // type-casting operator
  operator T&()              { return *data(); }
  operator T const &() const { return *data(); }

  // member forward
  T* operator->() { return data(); }
  T* const operator->() const { return data(); }

  // Storage zone
  private:
  unsigned char buffer[buffer_size];
};

struct foo
{
  foo(double v =0.) : value(v) {}
  foo(const char* str) : value(1./strlen(str)) {}

  double value;
  bool b;

  void display() const { cout << "value = " << value << endl; }
};

int main()
{
  padded<foo,16> f("lol");

  cout << sizeof(foo) << endl;
  cout << sizeof(f) << endl;
  f->display();
  f->b = false;
}


Output:
1
2
3
12
16
value = 0.333333


Create a new paste based on this one


Comments: