How to calculate structure laying in C ++ 11 at compile time?

PROBLEM

I have std :: vector gazillion Foo's

struct Foo { int m_i; char m_c; char m_padding[3]; // want to replace this }; 

I can write this piece of contiguous Foo quickly in binary form in just one shot.

My problem is that if I do not explicitly specify this m_padding, compute it and clear it myself, valgrind will complain about uninitialized entries.

Question

Is it possible to write a template class in C ++ 11 that will compute this add-on for me at compile time?

If so, I can simply add it at the end of my whole Foo and automatically initialize / clear them without complaining from valgrind.

I can do this manually by calculating sizeof (padding) = sizeof (Foo) - sum (sizeof (parts)), but it would be nice to create some class for this calculation, since all the information is available at compile time.

For simplicity, suppose Foo has a trivial layout (type_traits is an important but tangent problem). Also, ignore ordering issues / cross-platform issues.

Possible approach

This does not answer my initial question directly, but the hvd suggestion implies a simpler approach that seems to work for some simple test cases I tried:

 template<typename T> struct BZero { BZero() { std::memset( this, 0, sizeof( T )); } }; struct Foo : public BZero<Foo> { int m_i; char m_c; }; 
+7
c ++ sizeof c ++ 11
source share
2 answers

Well, I see two ways:

  • Use the union your class and a char array the size of a class
  • Use the template class and metaprogramming to figure out all the shims

Needless to say, the first seems a lot easier, so here you go:

 template <typename T> class ZeroedClass { public: template <typename... Args> ZeroedClass(Args&&... args) { new (&_.t) T(std::forward<Args>(args)...); } // Need other special members as well ~ZeroedClass() { _.t.~T(); } // Accessors T& access() { return _.t; } T const& get() const { return _.t; } private: union U { U() { memset(this, 0, sizeof(T)); } char buffer[sizeof(T)]; T t; } _; }; // class ZeroedClass 
+3
source share

Not sure what I understood well about this:

 struct FooBase { int i; char c; }; template<typename T, size_t total> struct padded : public T { char pad[total-sizeof(T)]; }; typedef padded<FooBase, 8> Foo; 
0
source share

All Articles