首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

运用字符串作为函数模板实参

2012-10-31 
使用字符串作为函数模板实参对于非引用类型的参数,在实参演绎的过程中,会出现数组到指针(array-to-pointer

使用字符串作为函数模板实参
对于非引用类型的参数,在实参演绎的过程中,会出现数组到指针(array-to-pointer)的类型转换(这种转型通常也被称为decay(退化))

#include<string>#include<iostream>using namespace std;/*  比较两个字符串的地址,而不是它们的字典顺序,这也是我们趋向使用如std::string的字符串类,  而不使用C风格字符串类的另一个原因*/template<typename T>inline T const& max(T const& a,T const& b){    return a<b?b:a;}template<typename T>inline T max2(T a,T b){    return a<b?b:a;//比较字典顺序}int main(){    string s;    string s1="abc",s2="d";    cout << ::max("apple","peach") << endl;    //cout << ::max("apple","tomato") << endl;//: error: no matching function for call to ‘max(const char [6], const char [7])’    cout << ::max(s1,s2) << endl;    cout << ::max2("d","c") << endl;}appledc

热点排行