I have an enum with variables names v1, v2..., vn, and each name has a corresponding class with the same name. I want to find, in compile time (even though I don't know if it's possible in run time either), the sum of the sizeof of these classes, as in the example below. Can you do this using templates or the preprocessor?
enum class Enum
{
First,
A = First,
B,
C,
Last
};
class A
{
// ...
};
class B
{
// ...
};
class C
{
// ...
};
constexpr size_t GetTotSumSizeOf()
{
// iterate from Enum::First to Enum::Last, summing sizeof the corresponding class
}
static constexpr size_t TotSum = GetTotSumSizeOf();
c++ does not allow you to iterate over enum class directly. so you can achiene the desired result by creating a helper struct that maps each enum value to its correponding class and then recursively compute the sum using templates. create a template specialization of the EnumToClass struct for each enum value. and use the GetSizeOfHelper template function that recursively computes the sum of th size of the corresponding class.finally use GetToSumSizeof function to call the recursive function and wrap it.
#include <type_traits>
#include <iostream>
enum class Enum
{
First,
A = First,
B,
C,
Last
};
class A
{
// ...
};
class B
{
// ...
};
class C
{
// ...
};
template<Enum E>
struct EnumToClass;
template<>
struct EnumToClass<Enum::A>
{
using Type = A;
};
template<>
struct EnumToClass<Enum::B>
{
using Type = B;
};
template<>
struct EnumToClass<Enum::C>
{
using Type = C;
};
template<Enum E>
constexpr size_t GetSizeOfHelper()
{
if constexpr (E == Enum::Last)
{
return 0;
}
else
{
using ClassType = typename EnumToClass<E>::Type;
return sizeof(ClassType) + GetSizeOfHelper<static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(E) + 1)>();
}
}
constexpr size_t GetTotSumSizeOf()
{
return GetSizeOfHelper<Enum::First>();
}
static constexpr size_t TotSum = GetTotSumSizeOf();
int main()
{
// Use TotalSum
char buffer[TotSum];
// Print the value of TotSum
std::cout << "Total size of the classes: " << TotSum << std::endl;
// Example usage of buffer
A* a_ptr = reinterpret_cast<A*>(&buffer[0]);
B* b_ptr = reinterpret_cast<B*>(&buffer[sizeof(A)]);
C* c_ptr = reinterpret_cast<C*>(&buffer[sizeof(A) + sizeof(B)]);
}