如何确定函数的返回值在编译时选择可能的选项

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

本文关键字:选择 选项 何确定 函数 返回值 编译      更新时间:2023-10-16

我有两个几乎相同的函数,它们接收与参数相同的结构。我的功能的非常简化的版本如下:

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

如何在不使用"如果"的情况下在编译时处理此操作?预先感谢。

使用指针作为参数的指针(或仅具有额外参数的正常函数):

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