Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.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++ 打印模板元编程的静态变量_C++_Compiler Errors_Template Meta Programming_Static Variables - Fatal编程技术网

C++ 打印模板元编程的静态变量

C++ 打印模板元编程的静态变量,c++,compiler-errors,template-meta-programming,static-variables,C++,Compiler Errors,Template Meta Programming,Static Variables,我有以下阶乘实现: #include <iostream> template <int n> struct factorial{ static const int res = n*factorial<n-1>::res; }; template <> struct factorial<0>{ static const int res = 1; }; int main(){ std::cout << fact

我有以下阶乘实现:

#include <iostream>

template <int n> struct factorial{
  static const int res = n*factorial<n-1>::res;
};

template <> struct factorial<0>{
  static const int res = 1;
};

int main(){
  std::cout << factorial<5>::res << '\n';
  return 0;
}
#包括
模板结构阶乘{
静态常数int res=n*阶乘::res;
};
模板结构阶乘{
静态常数int res=1;
};
int main(){

std::cout如果允许选项
-Werror
,或者如果警告被视为错误,则:

#include <iostream>

template <int n> struct factorial{
  static const int res = n*factorial<n-1>::res;
};

template <> struct factorial<0>{
  static const int res = 1;
};

int main(){
  char x[factorial<5>::res];
  return x[sizeof(x)];
}
#包括
模板结构阶乘{
静态常数int res=n*阶乘::res;
};
模板结构阶乘{
静态常数int res=1;
};
int main(){
charx[factorial::res];
返回x[sizeof(x)];
}
将产生错误/警告

错误:“x[120ul]”在此函数中未初始化使用[-Werror=uninitialized]

使用gcc 5.3或

错误:数组索引120超过了数组的末尾(包含120个元素)[-Werror,-Warray界限]


使用clang 3.8.

可以使用已声明但未定义的模板将值作为编译时错误打印出来

template<int n>
class display;

template<int n> struct factorial{
    static const int res = n*factorial<n-1>::res;
};

template<> struct factorial<0>{
    static const int res = 1;
};

int main()
{
    display<factorial<5>::res> value;
}
模板
课堂展示;
模板结构阶乘{
静态常数int res=n*阶乘::res;
};
模板结构阶乘{
静态常数int res=1;
};
int main()
{
显示值;
}
g++输出:

g++ -std=c++11 fact.cxx
fact.cxx: In function ‘int main()’:
fact.cxx:14:29: error: aggregate ‘display<120> value’ has incomplete type and cannot be defined
  display<factorial<5>::res> value;
                             ^
g++-std=c++11 fact.cxx
fact.cxx:在函数“int main()”中:
事实.cxx:14:29:错误:聚合“显示值”的类型不完整,无法定义
显示值;
^

如果您允许
-Werror
,这就可以了。
static\u assert
可能会有帮助,如果这不是作弊的话。@BaummitAugen:↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓@LightnessRacesinOrbit好吧,我猜在我不能完全摆脱“可能对OP没有用处”之后:)这对于显示整数非常好。我认为对于显示double(即,对于pi或其他的模板元编程计算)我可以做一些类似“staticcharc=x”的事情,如果x不是一个整体,它将打印一条警告number@xdavidliu我不知道如何在我头顶上做这件事,我会去睡觉的。你可以把它作为一个后续问题发布,如果没有人回答,请随意在这里给我一个链接,我会考虑的明天。你的想法可能只包括类型,而不是值,但你自己看看。