Skip to main content


Showing posts from November, 2022

The Visitor pattern

What is visitor pattern? 1.      It encapsulates an operation executed on an object hierarchy in an object. That says, it allows to add   methods to classes of different types without much altering to those classes. 2.        Enables to define new operations without changing the object hierarchy. Use-Case: a. Operations shall be performed on object hierarchy b. The operations change frequently but object hierarchy is stable. Basic UML Class Diagram:         Visitor: ·   Defines the visit operation on the object structure     Tax Visitor: ·   Implements the visit operation for each type of object     Visitable: ·   Defines the accept operation which takes visitor as an argument      Visitable Element(s):                    ·   Implements accept operations        The Visitor pattern has two types of hierarchies . The object hierarchy (Visitable elements) and the operation hierarchy (TaxVisitor). The object hierarchy is pretty stable, but operation hierarchy may

Variadic template class to add numbers recursively during compilation

 The idea of having a class to add numbers (variable parameters) during compilation time recursively. Also wanted to restrict types to a single type while sending parameters to class member function. That said, if we mix int, float and double types to add function shall result in compilation error. How do we achieve this. The below is the code which actually helps to achieve this: <code> #include < fmt/format.h > template < typename T> class MyVarSumClass{     private :         T _sum = 0 ;     public :         template < typename ... TRest>         T add(T num, TRest... nums){             static_assert (std::conjunction<std::is_same<TRest, T>...>{}); /* Assert fails                if types are different */             _sum += num;             return add(nums...); // Next parameter packs gets picked recursively         }         // Base case         T add(T num){             _sum += num;             return _sum;         } }; int main() {     My