C++ 静态断言负整数 #包括 使用名称空间std; 样板 constexpr int pow2T() { 静态_断言(事实
失败。显然,C++ 静态断言负整数 #包括 使用名称空间std; 样板 constexpr int pow2T() { 静态_断言(事实,c++,static-assert,C++,Static Assert,失败。显然,1
1<0
和2<0
都是false
顺便说一句,此函数计算
2^x
,而不是x^2
要计算这两个分支,您必须进行专门化:
#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;
}
模板
constexpr int pow2T()
{
静态断言(事实>=0,“错误”);
返回功率2t()*2;
}
样板
constexpr int pow2T()
{
返回1;
}
是一个输入错误吗?static\u assert与您的想法完全相反!如果条件为false,它将失败。它将断言条件为true。注意,如果您升级到C++14编译器,您可以使用迭代(循环)而不是递归函数调用。@potatostater:或者干脆(1u我的编译器同意你的看法。但你能说一下原因吗?:版本没有按预期工作?考虑到我试图只计算powT(2)。pow2T
需要pow2T
,这需要pow2T
。但是pow2T
也需要pow2T
,因为这两个分支是相互关联的(即使未对其进行评估)。
template <int fact>
constexpr int pow2T()
{
static_assert(fact >= 0, "error");
return pow2T<fact - 1>() * 2;
}
template <>
constexpr int pow2T<0>()
{
return 1;
}