samol
samol

Reputation: 20640

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

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.

Upvotes: 4

Views: 175

Answers (4)

bolov
bolov

Reputation: 75874

It's funny how the simplest solutions will sometimes just evade us. If you "will only use fieldA and will never use fieldB" then why not:

void do_stuff(double& fieldA)
{
   fieldA; // I will only use fieldA and will never use fieldB
}

void test()
{
    typeA a{};
    typeB b{};

    do_stuff(a.fieldA);
    do_stuff(b.fieldA);
}

...

Upvotes: 0

HugoTeixeira
HugoTeixeira

Reputation: 4884

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

Upvotes: 9

Rom
Rom

Reputation: 4199

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

Upvotes: 9

templatetypedef
templatetypedef

Reputation: 373402

You can use the template system for this:

 template <typename T> void do_stuff(const T& val) {
     // Use val.fieldA
 }

Here, if you call do_stuff on an object that has a field named fieldA, this will compile just fine and do what you want. If you try calling it on something without a fieldA member, this won’t compile and will report an error.

Upvotes: 3

Related Questions