Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153972
  • 博文数量: 37
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 380
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-13 18:49
文章分类

全部博文(37)

文章存档

2010年(1)

2009年(19)

2008年(17)

我的朋友

分类: C/C++

2009-11-03 15:48:43

偏特化理解


#include

using namespace std;


template

struct test {


test() {

cout << "io" << endl;

}

};


template

struct test {


test() {

cout << "* io" << endl;

}

};


template

struct test {


test() {

cout << "*& io" << endl;

}

};


int main() {

testobj;

return 0;

}


当偏特化时,通过类名后面的< >指定,例如struct test

注意偏特化之前必须有一个没有任何偏特化参数的声明。例如下面的代码编译就会出错

#include

using namespace std;


template typename O>

struct test {


test() {

cout << "* io" << endl;

}

};


int main() {

testobj;

return 0;

}


偏特化和默认模版参数相区分

//这是对一个一直的模版类偏特化

template

struct test {


test() {

cout << "* io" << endl;

}

};


//这里是默认模版参数

template

struct test {


test() {

cout << "* io" << endl;

}

};


当偏特化时,偏特化参数必须和最初声明的参数一致,下列代码就会编译失败

#include

using namespace std;


template

struct test {


test() {

cout << "io" << endl;

}

};


template

struct test {


test() {

cout << "* io" << endl;

}

};



int main() {

testobj;

return 0;

}



偏特化代码的模版参数不一定和最初的声明一致,下列代码可以编译通过

#include

using namespace std;


template

struct test {


test() {

cout << "io" << endl;

}

};


template

struct testI*> {


test() {

cout << "* io" << endl;

}

};



int main() {

testobj; //输出"* io"

return 0;

}



偏特化主要对模版参数进行 指针(*),不可变(const)等的限定

阅读(878) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~