Advertisement
Korotkodul

logic_logic.cpp

Mar 16th, 2025
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <stdexcept>
  2.  
  3. #include "logic.h"
  4.  
  5.  
  6. namespace Logic {
  7.  
  8. ElemInput::operator bool () const
  9. {
  10.   if (elem)
  11.     return inv ? !*elem : *elem;
  12.   else
  13.     return inv;
  14. }
  15.  
  16.  
  17. void Element::set (bool value)
  18. {
  19.   if (inverted_out)
  20.     value = !value;
  21.  
  22.   if (out != value)
  23.   {
  24.     out = value;
  25.  
  26.     if (cb)
  27.       cb(*this);
  28.  
  29.     for (auto elem : outputs)
  30.       elem->calc();
  31.   }
  32. }
  33.  
  34.  
  35. Element& operator>> (Element& lhs, Operation& rhs)
  36. {
  37.   check_loop(rhs, lhs);
  38.  
  39.   rhs.inputs.push_back(ElemInput{lhs, false});
  40.   lhs.outputs.push_back(&rhs);
  41.  
  42.   rhs.calc();
  43.   return rhs;
  44. }
  45.  
  46. Element& operator>> (Element& lhs, Connection rhs)
  47. {
  48.   check_loop(rhs.oper_elem, lhs);
  49.  
  50.   rhs.oper_elem.inputs.push_back(ElemInput{lhs, rhs.inverted});
  51.   lhs.outputs.push_back(&rhs.oper_elem);
  52.  
  53.   rhs.oper_elem.calc();
  54.   return rhs.oper_elem;
  55. }
  56.  
  57.  
  58. void check_loop (const Element& loop, const Element& elem)
  59. {
  60.   // checking if elem is the loop
  61.   if (&loop == &elem)
  62.     throw std::runtime_error{"loop detected in connections of logic elements"};
  63.  
  64.   for (const auto& output : loop.get_outputs())
  65.     check_loop(*output, elem);
  66. }
  67.  
  68.  
  69. void Source::calc ()
  70. {
  71.   // nothing to do here
  72. }
  73.  
  74.  
  75. void And::calc ()
  76. {
  77.   bool res{ get_inputs().size() != 0 };
  78.  
  79.   for (const auto& input : get_inputs())
  80.   {
  81.     if (!input)
  82.     {
  83.       res = false;
  84.       break;
  85.     }
  86.   }
  87.  
  88.   set(res);
  89. }
  90.  
  91. void Or::calc ()
  92. {
  93.   bool res{ false };
  94.  
  95.   for (const auto& input : get_inputs())
  96.   {
  97.     if (input)
  98.     {
  99.       res = true;
  100.       break;
  101.     }
  102.   }
  103.  
  104.   set(res);
  105. }
  106.  
  107. void Xor::calc ()
  108. {
  109.   bool res{ false };
  110.  
  111.   for (const auto& input : get_inputs())
  112.   {
  113.     if (input)
  114.     {
  115.       res = !res;  // переключаем состояние (XOR)
  116.     }
  117.   }
  118.  
  119.   set(res);
  120. }
  121.  
  122. } // namespace Logic
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement