struct typeA
{
double fieldA;
}
struct typeB
{
double fieldA;
double fieldB;
}
void do_stuff(typeA or typeB input)
{
input.fieldA // I will only use fieldA and will never use fieldB
}
It is performance sensitive so I don't want to convert it into a common type first.
You can template the do_stuff
function and the compiler will check the implementation for you. If the field isn't available you will get an error message. Here is a complete example:
struct typeA
{
double fieldA;
};
struct typeB
{
double fieldA;
double fieldB;
};
template <typename T>
void do_stuff(T& input)
{
input.fieldA = 10.0;
}
int main() {
typeA a;
do_stuff(a);
typeB b;
do_stuff(b);
}
Note: Remember to add the semi-colon ;
at the end of the struct
definition (otherwise it won't compile).
There is no performance hit if you DO use a common type, like this:
struct typeA
{
double fieldA;
};
struct typeB: typeA
{
double fieldB;
};
void do_stuff(typeA & input)
{
input.fieldA; // I will only use fieldA and will never use fieldB
}
You will only start seeing performance hit once you start using virtual methods. Unless and until you do that -- no perf costs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With