c++ - 放宽对枚举类和 bool 模板参数的 constexpr 要求

标签 c++ templates

考虑其中有一个函数 accumulate 的代码,该函数执行调度程序函数 process 的繁重工作。 accumulate 函数在热循环中测试参数,因此参数是模板化的。

enum class Op {
  Multiply,
  Add
};

template<Op op>
int accumulate(const std::vector<int> &vec) {
  int a = op == Op::Multiply ? 1 : 0;
  for (int v : vec)
    if constexpr (op == Op::Add) a += v; else a *= v;
  return a;
}

int process(const std::vector<int> &vec, Op op) {
  return accumulate<op>(vec);
}

您可能已经注意到此代码无法编译,因为从进程传递的模板参数不是 constexpr。但是,当模板参数是 bool 或特别是枚举类时,没有理由不编译它。

这样的代码在实践中经常出现,当一个函数执行繁重的工作有多个变体时(我们只想在代码库中保留一个拷贝)。是否有建议或讨论使此类代码在未来有效?

(C++ 有太多的特性,尽管缺少我需要的这个特性 :p )

最佳答案

However, when the template parameter is a bool or, especially, an enum class there is no reason why this shouldn't be compiled.

当参数是一个bool 或一个enum 且只有很少的值时,没有什么可以禁止您选择带有if开关

int process1 (const std::vector<int> &vec, bool b) {
  if ( b == true )
     return accumulate<true>(vec);
  else
     return accumulate<false>(vec);
}


int process2 (const std::vector<int> &vec, Op op) {
  switch ( op ) {
     case Op::Multiply:
        return accumulate<Op::Multiply>(vec);
        break;

     case Op::Add:
        return accumulate<Op::Add>(vec);
        break;

     // other cases

     // default
  }
} 

关于c++ - 放宽对枚举类和 bool 模板参数的 constexpr 要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727911/

相关文章:

c++ - 在不同线程之间通过 (c++) openmp 共享信息

c++ - 如何更正此程序中的重载赋值?

c++ - pimpl 是否与匿名命名空间兼容?

c++ - 当 C 中的对象 vector 中有太多 lua_state 时,lua_close() 崩溃

c++ - 奇怪的模板演绎

angular - 模拟单元测试的 <ng-template> - Angular 2

c++ - 找到其他节点的最快方法

c++ - 为数组重载运算符<<

具有嵌套表达式模板的 C++ 类

c++ - 类型 T 的构造函数