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

xda*_*liu 4 c++ compiler-errors static-variables template-meta-programming

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,此代码成功编译并输出120.但是,出于纯粹自我享受的原因,我想改为使其编译,而是在编译器的错误消息中显示120.

是否有一个简单的语法错误我可以刻意进入我的代码,使其无法编译,但仍然在编译器错误消息中打印5 !,即120的值?

我预计答案可能依赖于编译器; 我目前正在使用Xcode Mac OSX附带的g ++,其中iirc是clang的前端.

小智 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;
}
Run Code Online (Sandbox Code Playgroud)

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;
                             ^
Run Code Online (Sandbox Code Playgroud)