No, there is no reflection in C++, what you want is not possible.
You can however make every class conforming to an interface defined you. Although this requires you to provide the information manually:
struct Foo
{
uint16_t bar;
char bar2;
//maybe you want to return a typeid hash here instead of a string
static std::map<std::string, std::string> GetMembers()
{
return {("bar", "uint16_t"), ("bar2", "char")};
}
}
A code-generator could do this job for you by generating an AST and than inserting the above piece of code.
For a more advanced approach I would return a std::vector<MemberInfo>
with MemberInfo
being a class holding all relevant informations.
Such an approach could look like:
struct MemberInfo
{
std::string m_name;
size_t m_size;
};
template<typename T>
struct Reflection;
template<>
struct Reflection<Foo>
{
static std::vector<MemberInfo> GetMembers()
{
return {{"bar", sizeof(decltype(Foo::bar))}, {"bar2", sizeof(decltype(Foo::bar2))}}
}
};
template<typename T>
void PrintMembers()
{
for (auto& member : Reflection<T>::GetMembers())
{
std::cout << "name: " << member.m_name << " size: " << member.m_size << std::endl;
}
}