4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
15 #include <boost/assert.hpp>
16 #include <boost/bind.hpp>
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
28 * The two template arguments should be of different types.
30 template<typename T1, typename T2>
34 typedef T1 first_argument_type;
36 typedef T2 second_argument_type;
38 typedef std::pair<T1, T2> MapPair;
40 typedef std::vector<MapPair> Map;
43 Translator(T1 const & t1, T2 const & t2)
44 : default_t1(t1), default_t2(t2)
47 /// Add a mapping to the translator.
48 void addPair(T1 const & first, T2 const & second) {
49 map.push_back(MapPair(first, second));
51 // Add the contents of \c other
52 void add(Translator const & other) {
53 if (other.map.empty())
55 map.insert(map.end(), other.map.begin(), other.map.end());
58 /// Find the mapping for the first argument
59 T2 const & find(T1 const & first) const {
60 BOOST_ASSERT(!map.empty());
62 // For explanation see the next find() function.
63 typename Map::const_iterator it =
64 std::find_if(map.begin(), map.end(),
65 boost::bind(std::equal_to<T1>(),
66 boost::bind(&MapPair::first, _1),
70 if (it != map.end()) {
77 /// Find the mapping for the second argument
78 T1 const & find(T2 const & second) const {
79 BOOST_ASSERT(!map.empty());
81 // The idea is as follows:
82 // find_if() will try to compare the data in the vector with
83 // the value. The vector is made of pairs and the value has
84 // the type of the second part of the pair.
85 // We thus give find_if() an equal_to functor and assign to
86 // its second post the value we want to compare. We now
87 // compose the equal_to functor with the select2nd functor
88 // to take only the second value of the pair to be compared.
90 // We can depict it as follows:
91 // equal_to(select2nd(pair) , second)
92 typename Map::const_iterator it =
93 std::find_if(map.begin(), map.end(),
94 boost::bind(std::equal_to<T2>(),
95 boost::bind(&MapPair::second, _1),
114 #endif // TRANSLATOR_H