Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 919
samol Avatar asked Nov 29 '22 08:11

samol


2 Answers

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).

like image 29
HugoTeixeira Avatar answered Dec 05 '22 18:12

HugoTeixeira


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

like image 161
Rom Avatar answered Dec 05 '22 19:12

Rom