下面有一个例子:
- #include <iostream>
- using namespace std;
- int fa(){ cout<<"fa()"<<endl; return 1;}
- int fb(){ cout<<"fb()"<<endl; return 2;}
- int fc(){ cout<<"fc()"<<endl; return 3;}
- int main(){ cout<<fa()<<fb()<<fc()<<endl; return 0;}
- 输出
- fc()
- fb()
- fa()
- 123
这个模型和stack的执行方式是一样的。
这个以前没有注意过,现在还是要记好了。
下面还有个例子据说是一道人人网的面试题目:
- #include <iostream>
- using namespace std;
- int g=0;
- template<typename T, int nFlag>
- int foo()
- {
- int i = nFlag;
- static int value = ++g;
- return value;
- }
- int main()
- {
- cout<<foo<int, 0>()<<foo<bool, 1>()<<foo<float, 2>()<<foo<bool, 3>()<<foo<int, 4>()<<foo<char, 5>();
- cout<<endl;
- return 0;
- }
运行的结果是234321
下面是分析如何得到的:cout是从后向前执行,<<操作符的递归调用,先递归执行的是最后一个,么参数压栈的顺序是从右向左。这样foo<char>()会先调用,全局变量g变成1.之后foo<int>会给value初始 化为2,foo<bool>中value就是3,foo<float>中的value也会初始化为4.接下来的 foo<boo>中的value是不会再初始化,而是使用上次的值,所以仍为3.