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

函数模板特化有关问题

2012-04-15 
函数模板特化问题//模板函数C/C++ codetemplatetypename T void ExampleProc(const T& a1, const T& a2)

函数模板特化问题
//模板函数

C/C++ code
template<typename T> void ExampleProc(const T& a1, const T& a2){    cout<<a1<<endl;    cout<<a2<<endl;}

//特化模板函数实例
C/C++ code
template<> void  ExampleProc<const string&>(const string& a1,const string& a2){    cout<<a1+a2+" hello world!"<<endl;}        const string str1="test1";    const string str2="test2";    const string &str3="test3";    const string &str4="test4";    ExampleProc(str1,str2);//1.这种参数形式不能自动调用特化函数实例    ExampleProc(str3,str4);2.这种参数形式也不能自动调用特化函数实例    ExampleProc<const string&>(str3,str4);//3.这样显示指定模板类型参数才能调用特化的那个版本

该怎么定义参数去调用这个特化函数实例呢?

[解决办法]

template<> void ExampleProc<const string&>(const string& a1,const string& a2)
{
cout<<a1+a2+" hello world!"<<endl;
}

============

换成:
template<> void ExampleProc<string>(const string& a1,const string& a2)
{
cout<<a1+a2+" hello world!"<<endl;
}
[解决办法]
你用重载不就行了
[解决办法]
探讨


恩这样就可以了, 我的那种方式问题出在哪呢?

[解决办法]
简单地说就是,自动参数推导解析过程不能推导出const string& 这个类型的模板参数.

原因见书

热点排行