How to solve this problem???

harry_qc 2002-10-24 07:16:22
I met a problem which confused me for a long time. Who can help me??
parts of code as followes:

#include < iostream >
#include <string.h>
using namespace std;

template<class T>
test(T fg){
if(strcmp("S",fg.c_str())==0)
cout<<"string\n";
if(fg==1)
cout<<"int\n";
}

int main(){

int intfg = 1;
test(intfg);
string str = "S";
test(str);
return 0;
}
...全文
35 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dragonfly 2002-10-30
  • 打赏
  • 举报
回复
调用test(intfg)的时候,模板函数被特化为
template<int>
test(int fg){
if(strcmp("S",fg.c_str())==0)
cout<<"string\n";
if(fg==1)
cout<<"int\n";
}
显然你现在的fg是没有.c_str函数的,所以不会通过编译。

另外,确实入上面所说,我看不出这段代码的意义所在!
学GP没有C++基础还是先量力而行的好!
yangkwch 2002-10-29
  • 打赏
  • 举报
回复
我觉得你还是直接声明成模板类对象吧,这样看着不是很舒服。
kxw 2002-10-26
  • 打赏
  • 举报
回复
c_str() is a member function of string class
it can't use in template parament fg.
ygangy 2002-10-25
  • 打赏
  • 举报
回复
在模板函数中,类型参数的类型应当前后一致。
fg.c_str()
fg==1
前后一致吗?
gawain 2002-10-25
  • 打赏
  • 举报
回复
朋友,说实话
这段子写得却实差强人意
#include <iostream >
#include <string>
using namespace std;

template<class T>
void test(T fg){
cout<<fg;
}

int main(){

int intfg = 1;
test(intfg);
string str = "Srtgerwterwter";
test(str);
return 0;
}
cwsheng 2002-10-24
  • 打赏
  • 举报
回复
这段代码编译就不会通过。
因为编译器在函数模板的实例化的时候会用传递过来的形参类型替代参数类型。也就是会成这样的格式:
test(int fg)
{
}
test(string fg)
{
}

65,203

社区成员

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

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