DetectorGraph  2.0
portuguesetranslator.cpp File Reference

A dictionary-based translator that uses shared memory in TopicStates. More...

Go to the source code of this file.

Detailed Description

A dictionary-based translator that uses shared memory in TopicStates.

Introduction

This examples implements a very basic translator based only on word replacements.

Using Shared Memory in TopicStates

DetectorGraph uses C++ copies to propagate information across Topics & Detectors. This is fine & desirable for small amounts of data but can become prohibitive for large objects. In such cases the recommended pattern is to wrap the large resource using an appropriate smart pointer (e.g. std::shared_ptr).

The one caveat is that, as Detectors start accessing shared memory, the DetectorGraph framework alone cannot guarantee the hermetic nature of detectors - a detector's data (i.e. the data a member pointer points to) may change even though no Evaluate('new value') for that member was called.

In cases where the large data piece only has only read-only use, a const_shared_ptr can be used to partially address the concern mentioned above.

In this example, the TranslationDictionary TopicState carries a large, immutable object and does so using a shared_ptr<const T>:

93 struct TranslationDictionary : public TopicState
94 {
95  TranslationDictionary()
96  : map(std::make_shared<Text2TextMap>())
97  {
98  }
99 
100  TranslationDictionary(const std::shared_ptr<const Text2TextMap>& aMapPtr)
101  : map(aMapPtr)
102  {
103  }
104 
105  bool Lookup(std::string inStr, std::string& outStr) const
106  {
107  Text2TextMap::const_iterator lookupIterator = map->find(inStr);
108  if (lookupIterator != map->end())
109  {
110  outStr = lookupIterator->second;
111  return true;
112  }
113  else
114  {
115  return false;
116  }
117  };
118 
119  std::shared_ptr<const Text2TextMap> map;
120 };

A different example that also uses this pattern is Fancy Vending Machine:

478 struct ChangeAvailable : public DetectorGraph::TopicState
479 {
480  ChangeAvailable() : mCoins(), mpChangeLookupTable() {}
481 
482  ChangeAvailable(const ChangeAlgo::CoinStock& aCoins, const std::shared_ptr<const ChangeAlgo::ChangeLookupTable>& aLookupTable)
483  : mCoins(aCoins)
484  , mpChangeLookupTable(aLookupTable)
485  {
486  }
487 
488  bool CanGiveChange(unsigned change) const
489  {
490  return mpChangeLookupTable->CanGiveChange(mCoins, change);
491  }
492 
493  ChangeAlgo::CoinStock mCoins;
494  std::shared_ptr<const ChangeAlgo::ChangeLookupTable> mpChangeLookupTable;
495 };
Base struct for topic data types.
Definition: topicstate.hpp:52

Architecture

This sample implements the following graph:

TextTranslatorGraph

Definition in file portuguesetranslator.cpp.