static_assert负整数

时间:2015-01-07 13:26:42

标签: c++ static-assert

#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;:

     

...

2 个答案:

答案 0 :(得分:7)

如果条件为false

static_assert会失败。显然,1 < 02 < 0都是错误的。

BTW,此函数计算2^x,而不是x^2

答案 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;
}