Is there a way for a C++ function to take two different types with same members?

  • A+
Category:Languages
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).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: