代码改变世界

STL标准程序库自学--第一课

2016-03-02 15:21  yrpapa  阅读(139)  评论(0)    收藏  举报

一 Template

1 第一个简单的例子

#include <iostream>

// call of overloaded 'max(char&, char&)' is ambiguous
// 其实,原因很简单,因为使用using namespace std所造成的,
// 因为std里面有max(char&, char&)这个函数,所以,会和它造成二义性,也就通不过编译了
//using namespace std;

template <class T>
const T& max(const T& a, const T& b);

int main(int argc, char** argv)
{
	std::cout << max(2, 1) << std::endl;	
}

template <class T>
const T& max(const T& a, const T& b){
	return a < b ? b : a;
}

2 非型别模板参数--Nontype Templates

bitset<32> flag32 // 32个空间
bitset<50> flag50 // 50个空间

这些bitsets由于使用不同的template参数,所有有不同的类型,不能互相赋值或比较(除非提供了相应的型别转换机制)