【问题标题】:How to determine a functions` return value choosing possible options at compile time如何在编译时选择可能的选项来确定函数的返回值
【发布时间】:2019-03-07 10:03:53
【问题描述】:

我有两个几乎相同的函数,它们接收相同的结构作为参数。 我的函数的一个非常简化的版本,如下所示:

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”,我如何在编译时处理这个问题?提前致谢。

【问题讨论】:

  • 一个 bool 模板参数和一个 if constexpr 应该可以完成这项工作。
  • 直接传递c.a/c.b 而不是bool ?
  • @Quentin 只有 Cpp-11
  • @zontragon 请记得适当标记:)
  • @Quentin 对不起,你是对的。

标签: c++ c++11


【解决方案1】:

使用指向成员的指针作为参数的模板(或只是带有额外参数的普通函数):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2011-01-22
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多