So, in terms of structures, the following will work:
#include <iostream>
#include <string>
struct A {
int x;
double y;
};
struct C {
A a_in_c{1};
};
struct D {
A a_in_d{2};
};
template<typename T>
void foo (T t) {
auto a = reinterpret_cast<A*>(&t);
std::cout << a->x << "!\n";
}
int main()
{
std::string name;
D d;
foo(d);
}
Keep in mind, however, that as long as serialization and de-serialization is done on one machine, it should work okay, but it gets tricky once you communicate between machines (endianess have to be taken into account, or more generally speaking memory layout). Additionally, following code will work only if A
is the first field within C
or D
structure.
From design perspective, it's wiser to name the fields the same, because you are kinda killing the purpose of templates and duck-typing consuming T t
like this.