今天在 Stack Overflow 上看到这道题,其实不难,只是看到大家答案,发现还是有很多可以学习的地方的,所以就摘过来学习一下了。

方法1:

 
  
  1. #include <iostream> 
  2. template <N> 
  3. struct NumberGeneration{ 
  4.   static void out(std::ostream& os) 
  5.   { 
  6.     NumberGeneration::out(os); 
  7.     os << N << std::endl; 
  8.   } 
  9. }; 
  10. template<> 
  11. struct NumberGeneration<1>{ 
  12.   static void out(std::ostream& os) 
  13.   { 
  14.     os << 1 << std::endl; 
  15.   } 
  16. }; 
  17. int main(){ 
  18.    NumberGeneration<1000>::out(std::cout); 

方法2:

//这个C编译通过,C++好像不行

 
  
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3.  
  4. void main(int j) { 
  5.   printf("%d\n", j); 
  6.   (&main + (&exit - &main)*(j/1000))(j+1); 

//这个可以

 
  
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3.  
  4. void f(int j) 
  5.     static void (*const ft[2])(int) = { f, exit }; 
  6.  
  7.     printf("%d\n", j); 
  8.     ft[j/1000](j + 1); 
  9.  
  10. int main(int argc, char *argv[]) 
  11.     f(1); 

方法3:

 
  
  1. void f2(int N) 
  2.     N && (f2(N-1), cout << N << '\n'); 
  3. int main() 
  4.     f2(1000);