Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 静态断言负整数 #包括 使用名称空间std; 样板 constexpr int pow2T() { 静态_断言(事实_C++_Static Assert - Fatal编程技术网

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