簡體   English   中英

如何在編譯時選擇可能的選項來確定函數的返回值

[英]How to determine a functions` return value choosing possible options at compile time

我有兩個幾乎相同的函數,它們接收相同的結構作為參數。 我的函數的一個非常簡化的版本,如下所示:

struct Container {
 int A;
 int B;
}

int return_A_dependent(Container c){
  //... identical code for A and B ...
  int common_for_A_and_B = 0;
  return common_for_A_and_B + c.A;
}

int return_B_dependent(Container c){
  // ... identical code for A and B ...
  int common_for_A_and_B = 0;
  return common_for_A_and_B + c.B;
}

兩個函數之間的唯一區別是它們的返回值取決於結構的不同變量。 我想在不進行運行時檢查的情況下組合這兩個函數。 就像傳遞一個標志參數並添加一個 if 語句來轉發返回值,如下所示:

int return_A_or_B(Container c, bool flag_A) {
 // ... identical code for A and B ...
  int common_for_A_and_B = 0;
  if (flag_A) {
    return common_for_A_and_B + c.A;
  }
  else {
    return common_for_A_and_B + c.B;
  }

我如何在不使用“if”的情況下在編譯時處理這個問題? 提前致謝。

使用指向成員的指針作為參數的模板(或只是帶有額外參數的普通函數):

template<int Container::* p_member> int
Work(Container c)
{
    int common_for_A_and_B = 0;
    return common_for_A_and_B + c.*p_member;
}

Work<&Container::A>(c);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM