簡體   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