打印用于模板元编程的静态变量



我有以下阶乘的模板元编程实现:

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

此代码编译成功并按预期输出 120。但是,出于纯粹的自我享受原因,我想让它编译,而是在编译器的错误消息中显示 120。

是否有一个简单的语法错误,我可以故意输入到我的代码中,让它无法编译,但仍在编译器错误消息中打印值 5!,即 120?

我预计答案可能会取决于编译器;我目前正在使用Xcode Mac OSX附带的g ++,iirc是clang的前端。

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

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

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

如果允许选项 -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)];
}

将产生错误/警告

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

使用 GCC 5.3 或

错误:数组索引 120

超过数组的末尾(包含 120 个元素)[-Werror,-Warray-bounds]

使用 clang 3.8。

最新更新