今天在 Stack Overflow 上看到这道题,其实不难,只是看到大家答案,发现还是有很多可以学习的地方的,所以就摘过来学习一下了。
方法1:
- #include <iostream>
- template <N>
- struct NumberGeneration{
- static void out(std::ostream& os)
- {
- NumberGeneration::out(os);
- os << N << std::endl;
- }
- };
- template<>
- struct NumberGeneration<1>{
- static void out(std::ostream& os)
- {
- os << 1 << std::endl;
- }
- };
- int main(){
- NumberGeneration<1000>::out(std::cout);
- }
方法2:
//这个C编译通过,C++好像不行
- #include <stdio.h>
- #include <stdlib.h>
- void main(int j) {
- printf("%d\n", j);
- (&main + (&exit - &main)*(j/1000))(j+1);
- }
//这个可以
- #include <stdio.h>
- #include <stdlib.h>
- void f(int j)
- {
- static void (*const ft[2])(int) = { f, exit };
- printf("%d\n", j);
- ft[j/1000](j + 1);
- }
- int main(int argc, char *argv[])
- {
- f(1);
- }
方法3:
- void f2(int N)
- {
- N && (f2(N-1), cout << N << '\n');
- }
- int main()
- {
- f2(1000);
- }
转载于:https://blog.51cto.com/printlife/571820