简体   繁体   中英

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.

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

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.

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);
}

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM