-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathTokenStruct.h
81 lines (59 loc) · 1.53 KB
/
TokenStruct.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef _TOKENSTRUCT_H_
#define _TOKENSTRUCT_H_
/*
T is either a pointer or a string
A token structure stores pointers but does not delete them!
*/
typedef std::map< std::string, unsigned > TokenMap;
template <typename T>
inline std::string getName( const T & t ) {
return t->name;
}
template <>
inline std::string getName<std::string>( const std::string & s ) {
return s;
}
template <typename T>
class TokenStruct {
public:
std::vector< T > tokens;
TokenMap tokenMap;
// represents the types of a typed list
StringVec types;
TokenStruct() {}
TokenStruct( const TokenStruct & ts )
: tokens( ts.tokens ), tokenMap( ts.tokenMap ), types( ts.types ) {}
void append( const TokenStruct & ts ) {
for ( unsigned i = 0; i < ts.size(); ++i )
insert( ts[i] );
types.insert( types.end(), ts.types.begin(), ts.types.end() );
}
unsigned size() const {
return tokens.size();
}
T & operator[]( std::size_t i ) {
return tokens[i];
}
const T & operator[]( std::size_t i ) const {
return tokens[i];
}
void clear() {
for ( unsigned i = 0; i < size(); ++i )
delete tokens[i];
tokens.clear();
tokenMap.clear();
}
unsigned insert( const T & t ) {
TokenMap::iterator i = tokenMap.insert( tokenMap.begin(), std::make_pair( getName( t ), size() ) );
tokens.push_back( t );
return i->second;
}
int index( const std::string & s ) const {
TokenMap::const_iterator i = tokenMap.find( s );
return i == tokenMap.end() ? -1 : i->second;
}
T get( const std::string & s ) const {
return tokens[index( s )];
}
};
#endif