#include <iostream>
using namespace std;
template <int fact>
constexpr int pow2T()
{
static_assert(fact < 0, "error");
return fact == 0 ? 1 : pow2T<fact - 1>() * 2;
}
constexpr int e2 = pow2T<2>();
int main(int argc, char *argv[])
{
cout << e2 << endl;
return 0;
}
尝试使用参数静态检查实现x^2
静态计算。
断言失败..为什么!?
/home/serj/work/untitled/main.cpp:-1:在函数&#39; constexpr int pow2T()[with int fact = 2]&#39;:
/home/serj/work/untitled/main.cpp:-1:在函数&#39; constexpr int pow2T()[with int fact = 1]&#39;:
...
答案 0 :(得分:7)
答案 1 :(得分:3)
评估2个分支,你必须做专业化:
template <int fact>
constexpr int pow2T()
{
static_assert(fact >= 0, "error");
return pow2T<fact - 1>() * 2;
}
template <>
constexpr int pow2T<0>()
{
return 1;
}