模版 无法显式专用化

cyclejdm 2012-03-27 03:16:06

#include <string>
template<typename T>
class tmp
{
public :
T max(const T&,const T&);
};

template<typename T>
T tmp<T>::max(const T&a,const T& b)
{
cout << "普通版本"<<endl;
return a;
}
template<>
class tmp<std::string>
{
public:
std::string max(const std::string&,const std::string&);
};

template<>
std::string tmp<std::string>::max(const std::string& a,const std::string& b)
{
cout << "特化版本"<<endl;
return a;
}

error C2910: “tmp<std::string>::max”: 无法显式专用化

特化模版的max函数有什么错误吗?
...全文
1269 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2012-03-27
  • 打赏
  • 举报
回复
去看看c++ template吧。里面对于特化的类的成员函数的定义方式有说明的。
对于特化的类的成员函数必须像普通的成员函数那样定义。每一个T出现的地方都必须用特化的类型代替。
pathuang68 2012-03-27
  • 打赏
  • 举报
回复
显式特化从来没在工作中用过。
www_adintr_com 2012-03-27
  • 打赏
  • 举报
回复
函数模版不需要特化, 用的是重载.
cyclejdm 2012-03-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 pengzhixi 的回复:]

或者
C/C++ code
template<typename T>
class tmp
{
public :
T max(const T&,const T&);
};

template<typename T>
T tmp<T>::max(const T&a,const T& b)
{
cout << "普通版本"<<endl;
re……
[/Quote]

特化版本的不需要 加template<> 而且还不能放在同一个文件中
pengzhixi 2012-03-27
  • 打赏
  • 举报
回复
或者
template<typename T>
class tmp
{
public :
T max(const T&,const T&);
};

template<typename T>
T tmp<T>::max(const T&a,const T& b)
{
cout << "普通版本"<<endl;
return a;
}
template<>
class tmp<std::string>
{
public:
std::string max(const std::string&,const std::string&);
};

std::string tmp<std::string>::max(const std::string& a,const std::string& b)
{
cout << "特化版本"<<endl;
return "hello";
}
www_adintr_com 2012-03-27
  • 打赏
  • 举报
回复


#include <string>
template<typename T>
class tmp
{
public :
T max(const T&,const T&);
};

template<typename T>
T tmp<T>::max(const T&a,const T& b)
{
cout << "普通版本"<<endl;
return a;
}
template<>
class tmp<std::string>
{
public:
std::string max(const std::string&,const std::string&);
};

std::string tmp<std::string>::max(const std::string& a,const std::string& b)
{
cout << "特化版本"<<endl;
return a;
}



函数模版不能特化,只能重载, 去掉 template<> 变成重载就 OK 了.
pengzhixi 2012-03-27
  • 打赏
  • 举报
回复
template<typename T>
class tmp
{
public :
T max(const T&,const T&);
};

template<typename T>
T tmp<T>::max(const T&a,const T& b)
{
cout << "普通版本"<<endl;
return a;
}
template<>
class tmp<std::string>
{
public:
std::string max(const std::string&,const std::string&){
cout << "特化版本"<<endl;
return "hello";
}
};

65,203

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧