首先看代码:改代码的用途是将map类型转化为json的一个node(json 是一种轻量级的数据交换格式,可以理解为另一种可以map套map的结构,表现形式为string串)。
<span style="font-size:18px;">#include <iostream>
#include <string>
#include <sys/time.h>
#include <time.h>
#include <map>
#include <list>
#include <stdlib.h>
#include "stdio.h"
#include "json_cpp/json.h"
using namespace std;
template<class T1, class T2> int parserMapToNode(const string& node_name, const map<T1, T2> &m, Json::Value &json) {
Json::Value node;
map<T1, T2>::const_iterator iter;//<span style="background-color: rgb(255, 0, 0);">这行代码出错,这行代码出错</span>
for(iter = m.begin(); iter != m.end(); iter++) {
Json::Value m_node;
m_node[iter->first] = Json::Value(iter->second);
node.append(m_node);
}
json[node_name] = node;
return 0;
}
void test_node() {
Json::Value top;
Json::Value data;
map<string, string> name_num;
name_num.insert(pair<string, string>("Frank", "1"));
name_num.insert(pair<string, string>("Lucy", "2"));
name_num.insert(pair<string, string>("Poom", "3"));
parserMapToNode("name_num", name_num, data);
vector<string> ve;
ve.push_back("hongbinxu1");
ve.push_back("baier2");
parserVectorToNode("ve", ve, data);
top["data"] = data;
cout << top << endl;
}
int main(void) {
test_node();
return 0;
}</span>
该该程序运行的话会报这样的错误:
test.cc: In function ‘int parserMapToNode(const std::string&, const std::map<T1, T2, std::less<_Key>, std::allocator<std::pair<const _Key, _Tp> > >&, Json::Value&)’:
test.cc:52: error: too few template-parameter-lists
test.cc:53: error: ‘iter’ was not declared in this scope
其主要原因在于编译器不认识map<T1, T2>到底是变量还是什么东西。所以编译不通过,在此我们需要在其使用之前加上typename,让系统知道map<T1, T2>是一种类型。这样便可以编译通过。
也就是该行代码改为:
<span style="font-size:18px;">typename map<T1, T2>::const_iterator iter;</span>
便可编译通过,系统到此时知道map<T1,T2>为一种数据类型,而非变量。
在此十分感谢玥哥的解答。
玥哥还发了一段,但是不是太懂。
typename另外一个作用为:使用嵌套依赖类型(nested depended name),如下所示:
class MyArray
{
public:
typedef int LengthType;
.....
}
template
void MyMethod( T myarr )
{
typedef typename T::LengthType LengthType;
LengthType length = myarr.GetLength;
}
这个时候typename的作用就是告诉c++编译器,typename后面的字符串为一个类型名称,而不是成员函数或者成员变量,这个时候如果前面没有typename,编译器没有任何办法知道T::LengthType是一个类型还是一个成员名称(静态数据成员或者静态函数),所以编译不能够通过。
编译器没有任何办法知道T::LengthType是一个类型还是一个成员名称(静态数据成员或者静态函数)
因为T::目前不知道是个什么类。
ps:写一点小心情,出校门第一家公司就这么合并了,妈了个蛋。