2 /* This file is part of
3 * =================================================
5 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich.
7 * Copyright 1995-2000 The LyX Team.
9 * This file Copyright 2000 Baruch Even
10 * ================================================= */
20 #include "support/LAssert.h"
22 // Functors used in the template.
25 template<typename T1, typename T2>
26 class equal_1st_in_pair {
29 equal_1st_in_pair(T1 const & value) : value_(value) {}
31 typedef std::pair<T1, T2> pair_type;
33 bool operator() (pair_type const & p) const {
34 return p.first == value_;
43 template<typename T1, typename T2>
44 class equal_2nd_in_pair {
47 equal_2nd_in_pair(T2 const & value) : value_(value) {}
49 typedef std::pair<T1, T2> pair_type;
51 bool operator() (pair_type const & p) const {
52 return p.second == value_;
60 /** This class template is used to translate between two elements, specifically
61 it was worked out to translate between an enum and strings when reading
64 The two template arguments should be of different types.
66 template<typename T1, typename T2>
70 typedef T1 first_argument_type;
72 typedef T2 second_argument_type;
74 typedef std::pair<T1, T2> MapPair;
76 typedef std::vector<MapPair> Map;
79 Translator(T1 const & t1, T2 const & t2)
80 : default_t1(t1), default_t2(t2)
83 /// Add a mapping to the translator.
84 void addPair(T1 const & first, T2 const & second) {
85 map.push_back(MapPair(first, second));
88 /// Find the mapping for the first argument
89 T2 const & find(T1 const & first) const {
92 // For explanation see the next find() function.
93 Map::const_iterator it =
94 std::find_if(map.begin(), map.end(),
95 equal_1st_in_pair<T1, T2>(first)
98 if (it != map.end()) {
105 /// Find the mapping for the second argument
106 T1 const & find(T2 const & second) const {
107 Assert(!map.empty());
109 // The idea is as follows:
110 // find_if() will try to compare the data in the vector with
111 // the value. The vector is made of pairs and the value has
112 // the type of the second part of the pair.
113 // We thus give find_if() an equal_to functor and assign to
114 // its second post the value we want to compare. We now
115 // compose the equal_to functor with the select2nd functor
116 // to take only the second value of the pair to be compared.
118 // We can depict it as follows:
119 // equal_to( select2nd(pair) , second)
120 Map::const_iterator it =
121 std::find_if(map.begin(), map.end(),
122 equal_2nd_in_pair<T1, T2>(second)