繁体   English   中英

有没有办法使C ++函数采用具有相同成员的两种不同类型?

[英]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
}

它对性能敏感,所以我不想先将它转换为通用类型。

您可以模板化do_stuff函数,编译器将为您检查实现。 如果该字段不可用,您将收到错误消息。 这是一个完整的例子:

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

注意 :记得添加分号; struct定义的末尾(否则它将无法编译)。

如果您使用常见类型,则没有性能损失,如下所示:

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
}

一旦开始使用虚拟方法,您才会开始看到性能受到影响。 除非并且直到你这样做 - 没有性能成本

您可以使用模板系统:

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

在这里,如果你在一个名为fieldA的字段的对象上调用do_stuff ,这将编译得很好并按你的意愿fieldA 如果您尝试在没有fieldA成员的情况下调用它,则无法编译并报告错误。

有趣的是,最简单的解决方案有时会逃避我们。 如果你“只使用fieldA并且永远不会使用fieldB”那么为什么不:

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

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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