C ++ Placement New with templates

Background

I am working on an embedded C ++ project in which I am creating a simple state machine using inheritance. The idea is that each state inherits from the base class State, and the state manager will create and destroy instances of the subclass during state transitions. To avoid using the heap, I would like to use a new layout with a statically allocated array.

Question

How can I use C ++ templates to size the largest subclass of state at compile time to create a static array of the appropriate size? I know this is possible because TouchGFX (C ++ Built-in GUI Library) uses the same method to manage Presenter and View subclass instances.

+3


source to share


1 answer


About what is done in touchGfx

I think that

typedef meta::TypeList< MainView,
                        meta::TypeList< LeftView,
                        meta::TypeList< RightView,
                        meta::TypeList< DownView,
                        meta::TypeList< UpView,
                        meta::Nil > > > >
                      > ViewTypes;

      

part for some purpose I don't understand globally, however with this trick it can know the maximum size of this place

In code



code (simplified just the way you want):

#include <stdlib.h>
#include <iostream>
template<typename ...All>
struct maxSize;

template<typename Member>
struct maxSize<Member>{
  static const size_t member_size = sizeof(Member);
  static const size_t size = member_size;
};

template <typename Member, typename... Rest>
struct maxSize<Member, Rest...> : maxSize<Rest...>{
  static const size_t member_size = sizeof(Member);
  static const size_t size = (member_size > maxSize<Rest...>::size ? (member_size) : (maxSize<Rest...>::size));
};

template<typename... sizeMax>
void* allocSpace() {
  return new char [maxSize<sizeMax...>::size];
}

int main(){
  allocSpace<char, char[10], int, double>();
  std::cout << maxSize<char, char[10], int, double>::size << " " << sizeof(int) << std::endl;
}

      

Edit

This was my code, or what I can do to order what you want, but the list of types certainly looks something like this:

struct NIL{
  static const size_t size =0;
};

template<typename Member, typename Tail>
struct typeList{
  static const size_t size = Tail::size > sizeof (Member) ? Tail::size : sizeof(Member);
};

      

+1


source







All Articles