为模板元编程打印静态变量

print static variable for template metaprogramming

我有以下 template metaprogramming 阶乘的实现:

#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 的前端。

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

将产生 error/warning

error: 'x[120ul]' is used uninitialized in this function [-Werror=uninitialized]

使用 gcc 5.3 或

error: array index 120 is past the end of the array (which contains 120 elements) [-Werror,-Warray-bounds]

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

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