您的位置:首页 > 编程语言 > C语言/C++

c++学习点滴4

2013-01-21 10:41 225 查看
一、函数模板

1. 一些注意事项
typedef double Type;
template <class Type>  // 1. 这里的Type会覆盖全局域中的Type名字。即这里的Type不是double
const Type& min(const Type& v1, const Type& v2) {

//typedef char Type; // 2. 不能再声明和模板参数类型同名的类型

Type tmp = v1 < v2 ? v1 : v2;

return tmp;
}

// 函数声明和定义中的参数类型名不必相同
template <typename T> void fun (const T& t1); // 声明
template <typename U> void fun(const U& t1); // 定义

2.函数模板的实例化

template<class T>
void fun(T t){
cout << "void fun(T t) "  << endl;
}

void test() {
// 函数模板在被调用或取地址的时候被实例化
fun(3); // 被实例化
void (*pf)(int) = &fun; // 被实例化
pf(10);
}

3. 对于如下函数模板定义
template<class T, int size>
void fun(T (&rarr)[size]){
}

void test(int arr[3]) {
//fun(arr); // error. arr是int*类型而非int[]类型
int arr2[] = {1,2,3};
fun(arr2);
}


二、explicit关键字

主要是用来禁止隐式转换。所有单参数构造函数、大多数情况下的拷贝构造函数都应该被声明为explicit

参考/article/7142207.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: