对c++primer 16.6.1的第4小节的代码说明

这段代码是这样的:

template<typename T>
int compare(const T& t1,const T& t2)
{
cout<<"范型"<<endl;
return 1;
}

int main()
{
  cout<<compare("hello","world")<<endl;
}


template<>

int compare<const char*>(const char* const &t1,const char* const &t2)

{
cout<<"特化"<<endl;
return 2;
}

我们可以把compare对const char*的特化版本放在main之前,然后看到它仍然是去重新实例话一个函数,而不是使用特化的函数,这是因为compare的函数参数是引用类型,而我们调用compare时是这样的,compare("hello","world"),那么当参数是引用时,常量字符串就不会主动转变成const char*指针,如果我们把compare的参数改为非引用类型的,那么compare("hello","world")就会调用特化版本,反之,"hello"和"world"调用范型函数时确定的类型是 const char *(&)[6],和下面的是同理

void print(const char* &p)

{

}

 

void print(const char* p)

{

}

假如上面2个函数都是合理的,当print("aaaa")时会调用哪个函数?从上面我们能得出,应该调用函数形参是非const的,因为这时是传值;如果只有第1个函数而我们print("aaa"),那么就会因为找不到对应的print函数而编译不通过

posted on 2013-04-17 17:27  紫金树下  阅读(120)  评论(0编辑  收藏  举报