考虑其中有一个函数 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/