函数模板能被定义在类中吗?

VincintCao 2002-12-06 04:41:06
template<class T1,class T2>
void test(T1 a,T2 b)
{
}
如果上面的函数是全局的,下面的调用
test<int,char>(0,'c');
就可以编译通过,如果上面的函数是类的成员,
那么即使在该类的另一成员函数内调用
test<int,char>(0,'c');
也会编译出错。用static也错,是什么原因?
...全文
105 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
deanjiang 2002-12-07
  • 打赏
  • 举报
回复
你是不是用的VC6?建议不要在VC6下用成员模板,VC6不支持。MSDN中明确写的。到了VC7就没问题了
lx_cyh 2002-12-07
  • 打赏
  • 举报
回复
TCPL 指<< THE C++ PROGRAMMING LANGUAGE>> 一书
VincintCao 2002-12-07
  • 打赏
  • 举报
回复
谢谢。
VincintCao 2002-12-06
  • 打赏
  • 举报
回复
如果我用自己的类的话,系统会自动推导吗?我如果不显示说明的话,会出现如下错误:
E:\software\implement\MTConsole\MTConsoleDlg.cpp(875) : fatal error C1001: INTERNAL COMPILER ERROR
(compiler file 'msc1.cpp', line 1794)
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
Error executing cl.exe.
显式说明的话,也会出错,不知道哪里出的问题。
VincintCao 2002-12-06
  • 打赏
  • 举报
回复
TO:liushmh(c++)
那如果我用自己的类,或者是别的vector,deque等呢?
liushmh 2002-12-06
  • 打赏
  • 举报
回复
t.test<int>(i);
这种东西,不是在这样用的,在编译的时候,系统会自动推导i是int型的,所以F就是int型.
template <typename F>
test<int>(F m)
{

}
这个叫做模板的特化,你怎么能把它放到调用里面。
VincintCao 2002-12-06
  • 打赏
  • 举报
回复
To:liushmh(c++)
你的代码的确可以通过,但是为什么把你的代码中的
t.test(i);
改成t.test<int>(i);
反而通不过了呢?

To:lx_cyh(hi)
什么是TCPL
我不懂电脑 2002-12-06
  • 打赏
  • 举报
回复
class tt
{
public:
template <class F>
void test(F m)
{cout<< m << endl;}
};

int main()
{
tt t;
int i = 9;
t.test(i);
system("PAUSE");
return 1;
}
lx_cyh 2002-12-06
  • 打赏
  • 举报
回复
可以。参见TCPL
liushmh 2002-12-06
  • 打赏
  • 举报
回复
可以。
class tt
{
public:
template <typename F>
void test(F m)
{cout<< m << endl;}
};

int main()
{
tt t;
int i = 6;
t.test(i);
system("PAUSE");
return 1;
}
Firstbyte 2002-12-06
  • 打赏
  • 举报
回复
你的class 不是类的意思 和typename 意思一样的!!!
VincintCao 2002-12-06
  • 打赏
  • 举报
回复
?我试过的,除非我的眼睛背叛了我的心!
liushmh 2002-12-06
  • 打赏
  • 举报
回复
你好象没有这样做 ?????

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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