我想描述使用模板优化这里.但是,随着bool模板参数的增加,实例化模板可能会有太多分支.如果你使用更大的枚举而不是bools,它会变得更加冗长.
#include <iostream>
using namespace std;
template <bool b1, bool b2>
int HeavyLoop_impl(int arg)
{
for (int i = 0; i < 10000000; i++)
{
// b1 is known at compile-time, so this branch will be eliminated
if (b1) { arg += 1; }
else { arg += 2; }
// b2 is known at compile-time, so this branch will be eliminated
if (b2) { arg += 10; }
else { arg += 20; }
}
return arg; …Run Code Online (Sandbox Code Playgroud)