传递模板类型参数时的问题

ronliu 2008-07-30 11:06:18
有一个函数,它的参数为类型未定的模板类,本例中vector<T>,但是传递时提示错误。
//1 instantiated from 'void wrap(const string&, const std::vector<T, std::allocator<_CharT> >&)[with T = int]'


#include <vector>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//将vector转化为一个字符串
template<typename T>
void wrap(const string& name, const vector<T>& value)
{ string _content;
typename vector<T, allocator<T> >::iterator iter;
iter = value.begin(); //1
for(; iter != value.end(); iter++)
_content += ":" + name + " " + toString(*iter);
_content += ")";
cout << _content;
};

template<typename T> string
toString(const T& t) //将T转化为string
{
ostringstream s;
s << t;
return s.str();
}

int main()
{
vector<int> vec;
for(int i = 0; i < 10; i++)
vec.push_back(i);
wrap("vec", vec);
}

...全文
86 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ronliu 2008-07-30
  • 打赏
  • 举报
回复
看来结贴快了也不是好事啊,后面还有这么多的回帖没法给分了。
ronliu 2008-07-30
  • 打赏
  • 举报
回复
我用的gcc编译器
tangshuiling 2008-07-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 akirya 的回复:]

typename vector <T, allocator <T> >::iterator iter;
改为
typename vector <T, allocator <T> >::const_iterator iter;
[/Quote]
既然函数的形参为const vector<T>& value,iter又声明为typename vector<T, allocator<T> >::iterator
那这句就肯定有问题iter = value.begin(); 型别有差异,一楼正解!!!
ronliu 2008-07-30
  • 打赏
  • 举报
回复
原来如此,搞定,送分,结贴,走人。回去睡个好觉!
seayou 2008-07-30
  • 打赏
  • 举报
回复

我这样调试可以通过啊
// kkk.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


#include <vector>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//将vector转化为一个字符串
template<typename T>
void wrap(const string& name, vector<T>& value)
{
string _content;
typename vector<T, allocator<T> >::iterator iter;
iter = value.begin();
for(; iter != value.end(); iter++)
_content += ":" + name + " " + toString(*iter);
_content += ")";
cout << _content;
}

template<typename T> string
toString(const T& t) //将T转化为string
{
ostringstream s;
s << t;
return s.str();
}

int main()
{
vector<int> vec;
for(int i = 0; i < 10; i++)
vec.push_back(i);
wrap("vec", vec);
return 0;
}
  • 打赏
  • 举报
回复

typename vector<T, allocator<T> >::iterator iter;
改为
typename vector<T, allocator<T> >::const_iterator iter;

64,651

社区成员

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

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