I have inherited a bunch of networking code that defined numerous packet types. I have to write a bunch of conversion functions that take structs of a certain type, and copy the values into other structs that have the same fields, but in a different order (as part of a convoluted partial platform bit order conversion thing -- don't ask). Also, I know that there may be better ways of expressing the conversion, etc. below, but I'm not concerned with those at the moment. Particularly, I cannot make convert take its output variable by reference, because I will be passing in bitfields, and that generates a compiler error.
So there are a bunch of structs like this:
struct foo {
int bar;
int baz;
};
struct foo_x86 {
int baz;
int bar;
};
And a bunch of functions like this, to convert between the two:
foo_x86 convert(const foo& in) { foo_x86 out; out.bar = in.bar; out.baz = in.baz; return out; }
This is all no big deal. The problem I have is this: there is also a template struct that looks something like this:
template <class T>
struct Packet {
HeaderType head;
T data;
};
There are a number of instantiations of this template, using packet types above as the template parameters, for example:
struct superfoo {
Packet<foo> quux;
};
struct superfoo_x86 {
Packet<foo_x86> quux;
};
Now, assuming that there exists a function foo_x86 convert(const foo&); is there any way to create a template function for handling Packet objects that calls this convert function?
For example, I want something that looks sort of like this:
template <class type_1, class type_2>
Packet<type_2> convert(const Packet<type_1>& in) {
Packet<type_2> out;
out.head = in.head;
out.data = convert(in.data);
return out;
}
That would work in a function like:
superfoo_x86 convert(const superfoo& in) {
superfoo_x86 out;
out.quux = convert(in.quux);
return out;
}
I want to be able to convert Packet objects without caring what type they are instantiated with, and I want to avoid having to declare separate convert functions for every possible Packet instantiation.
Is there anyway to do with with templates in C++?