LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 911|回复: 7

C++模板问题,请教大虾,在线等 - 已解决,感谢各位大侠的帮助

[复制链接]
发表于 2007-3-26 11:56:17 | 显示全部楼层 |阅读模式
  1. #include <iostream>
  2. #include <list>

  3. using namespace std;

  4. template<typename T>
  5. void output(T &l)
  6. {
  7.         for(T::const_iterator it = l.begin(); it != l.end(); ++it)
  8.                 cout << *it << endl;
  9. }


  10. int main()
  11. {
  12.         int ints[] = {10, 9, 8, 7, 6, 3};
  13.         list<int> lst(ints, ints + sizeof(ints)/sizeof(ints[0]));
  14.         output(lst);

  15.         return 0;
  16. }
复制代码


编译输出的结果为:
[root@localhost tmp]# g++ main.cpp
main.cpp: In function ‘void output(T&)’:
main.cpp:10: 错误:expected `;' before ‘it’
main.cpp:10: 错误:‘it’ 在此作用域中尚未声明
main.cpp: In function ‘void output(T&) [with T = std::list<int, std::allocator<int> >]’:
main.cpp:19:   instantiated from here
main.cpp:10: 错误:依赖名 ‘T::const_iterator’ 被解析为非类型,但实例化却产生了一个类型
main.cpp:10: 附注:如果您想指定类型,请使用 ‘typename T::const_iterator’


请问该问题该如何解决????
发表于 2007-3-26 12:18:09 | 显示全部楼层
  1. 编译输出的结果为:
  2. [root@localhost tmp]# g++ main.cpp
  3. main.cpp: In function ‘void output(T&)’:
  4. main.cpp:10: 错误:expected `;' before ‘it’
  5. main.cpp:10: 错误:‘it’ 在此作用域中尚未声明
  6. main.cpp: In function ‘void output(T&) [with T = std::list<int, std::allocator<int> >]’:
  7. main.cpp:19:   instantiated from here
  8. main.cpp:10: 错误:依赖名 ‘T::const_iterator’ 被解析为非类型,但实例化却产生了一个类型
  9. [color="Red"]main.cpp:10: 附注:如果您想指定类型,请使用 ‘typename T::const_iterator’[/color]
复制代码
回复 支持 反对

使用道具 举报

发表于 2007-3-26 15:54:51 | 显示全部楼层
格式问题
templete<class t>
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-3-28 09:47:54 | 显示全部楼层
Post by biosxjj
格式问题
templete<class t>


能否写出output函数的具体实现,多谢。我试着这样写过,但是函数无法实例化:
  1. template<typename T, typename Iter = std::list<T>::const_iterator>
  2. void output(const std::list<T> &l)
  3. {
  4. for(Iter it = l.begin(); it != l.end(); ++it)
  5. cout << *it << endl;
  6. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2007-3-28 10:28:58 | 显示全部楼层
请看二楼的红色部分
我觉编译器给出的提示已经很清楚了。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-3-28 10:35:12 | 显示全部楼层

可否给出一个具体的实现代码,我的template比较弱

g++的提示我看到了,但是仍然不清楚该怎么做,还请大侠能够给出个具体的实现,多谢
回复 支持 反对

使用道具 举报

发表于 2007-3-28 10:40:26 | 显示全部楼层
main.cpp:10: 错误:依赖名 ‘T::const_iterator’ 被解析为非类型,但实例化却产生了一个类型
main.cpp:10: 附注:如果您想指定类型,请使用 ‘typename T::const_iterator’
照这做就行了
将第10行的 T::const_iterator 改为 typename T::const_iterator
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-3-28 10:50:25 | 显示全部楼层

搞定了,没想到typename还可以这么用,今天又学了一招,多谢多谢

  1. #include <iostream>
  2. #include <list>

  3. using namespace std;

  4. template<typename T>
  5. void output(T &l)
  6. {
  7. for(typename T::const_iterator it = l.begin(); it != l.end(); ++it)
  8. cout << *it << endl;
  9. }


  10. int main()
  11. {
  12. int ints[] = {10, 9, 8, 7, 6, 3};
  13. list<int> lst(ints, ints + sizeof(ints)/sizeof(ints[0]));
  14. output(lst);

  15. return 0;
  16. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表