]> git.lyx.org Git - lyx.git/blob - src/support/Translator.h
Merge branch 'master' of git.lyx.org:lyx
[lyx.git] / src / support / Translator.h
1 // -*- C++ -*-
2 /**
3  * \file Translator.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Baruch Even
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef TRANSLATOR_H
13 #define TRANSLATOR_H
14
15 #include "support/lassert.h"
16
17 #include <vector>
18 #include <utility>
19
20
21 namespace lyx {
22
23 /**
24  * This class template is used to translate between two elements, specifically
25  * it was worked out to translate between an enum and strings when reading
26  * the lyx file.
27  *
28  * The two template arguments should be of different types.
29  */
30 template<typename T1, typename T2>
31 class Translator {
32 public:
33         ///
34         typedef T1 first_argument_type;
35         ///
36         typedef T2 second_argument_type;
37         ///
38         typedef std::pair<T1, T2> MapPair;
39         ///
40         typedef std::vector<MapPair> Map;
41         ///
42         typedef typename Map::const_iterator const_iterator;
43
44         ///
45         Translator(T1 const & t1, T2 const & t2)
46                 : default_t1(t1), default_t2(t2)
47         {}
48
49         /// Add a mapping to the translator.
50         void addPair(T1 const & first, T2 const & second)
51         {
52                 map.push_back(MapPair(first, second));
53         }
54
55         // Add the contents of \c other
56         void add(Translator const & other)
57         {
58                 if (other.map.empty())
59                         return;
60                 map.insert(map.end(), other.map.begin(), other.map.end());
61         }
62
63         /// Find the mapping for the first argument
64         T2 const & find(T1 const & first) const
65         {
66                 LASSERT(!map.empty(), return default_t2);
67                 const_iterator it = map.begin();
68                 const_iterator end = map.end();
69                 for (; it != end; ++it)
70                         if (it->first == first)
71                                 return it->second;
72                 return default_t2;
73         }
74
75         /// Find the mapping for the second argument
76         T1 const & find(T2 const & second) const
77         {
78                 LASSERT(!map.empty(), return default_t1);
79                 const_iterator it = map.begin();
80                 const_iterator end = map.end();
81                 for (; it != end; ++it)
82                         if (it->second == second)
83                                 return it->first;
84                 return default_t1;
85         }
86 private:
87         ///
88         Map map;
89         ///
90         T1 const default_t1;
91         ///
92         T2 const default_t2;
93 };
94
95
96 } // namespace lyx
97
98 #endif // TRANSLATOR_H