| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 997 人关注过本帖
标题:C++的函数模板是不是不能部分具体化?
只看楼主 加入收藏
iloveyn2000
Rank: 1
等 级:新手上路
帖 子:8
专家分:3
注 册:2012-7-29
结帖率:66.67%
收藏
已结贴  问题点数:20 回复次数:2 
C++的函数模板是不是不能部分具体化?
在C++primer plus的14章里讲到类模板可以部分具体化,如:
template<class T1, class T2>class Pair(T1, T2);
template<class T1>class Pair<int>(T1, int);
我有个小问题就是函数模板能否部分具体化:
template<class T1, class T2>void demo(T1 t1, T2 t2){cout<<"usual function template"<<endl;}
template<class T1>void demo<int> demo(T1 t1, int t2){cout<<"partial specialization template"<<endl;}
我在VS2010 里运行出现错误:
error C2768: “demo”: 非法使用显式模板参数
我想问问是我函数写错还是模板函数本身就无法部分具体化?
程序代码:
#include<iostream>
using std::cout;
using std::endl;

template <class T1, class T2, class T3>
void demo(T1 t1,T2 t2, T3 t3){
    cout<<"usual template "endl;
}

template<class T1, class T2>void demo<T1,T2,int>( T1 t2, T2 t3,int i){
    cout<<"partial specialization template "<<endl;
}

template <>
void demo<int,int,int>(int t1,int t2, int t3){
    cout<<" specialization template: "<<t1<<": "<<t2<<": "<<t3<<endl;
}
int main(){
    demo(1.1,2.2,3.3);
    demo(1.1,2.1,3);
    demo(1,2,3);
    getchar();
    return 0;
}
搜索更多相关主题的帖子: function 
2014-03-13 09:06
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:20 
函数可以重载,所以语法上没有必须加入偏特化的功能
程序代码:
#include <iostream>
using namespace std;

template<class T1, class T2, class T3>
void demo( T1 t1, T2 t2, T3 t3 )
{
    cout << "usual template " << endl;
}

template<>
void demo<int,int,int>( int t1, int t2, int t3 )
{
    cout << "specialization template" << endl;
}

template<class T1, class T2>
void demo( T1 t1, T2 t2, const char* t3 ) // 其实是重载
{
    cout << "partial specialization template" << endl;
}

int main()
{
    demo( 1.1, 2.2, 3.3 );
    demo( 1,   2,   3   );
    demo( 1.1, 2.1, "3" );

    return 0;
}

2014-03-13 10:59
iloveyn2000
Rank: 1
等 级:新手上路
帖 子:8
专家分:3
注 册:2012-7-29
收藏
得分:0 
回复 2楼 rjsp
谢谢回答。
2014-03-13 18:18
快速回复:C++的函数模板是不是不能部分具体化?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015281 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved