Metaprogramming Concepts and Applications

  • Introduction to Metaprogramming

    • Robertas Damaševičius, robertas.damasevicius@polsl.pl

    • Metaprogramming is an advanced programming technique focused on enhancing the capabilities and flexibility of software development. It allows developers to write code that manipulates other code, enabling powerful abstractions and automation.

  • Content of Lecture

    • Introduction to Metaprogramming: A foundational overview of what metaprogramming is, its benefits, and its applications in modern software development.

    • Historical Origins of Metaprogramming: Examining the evolution of metaprogramming from early macro systems to modern applications, tracing its roots and development over time.

    • Examples of Metaprogramming: Demonstrating practical uses of metaprogramming across various domains, showcasing real-world applications and use cases.

    • Languages and Metalanguages: Understanding the roles and relationships between programming languages (used for writing applications) and metalanguages (used for describing or manipulating other languages).

    • Role of Metaprogramming in Software Development: Assessing the impact and importance of metaprogramming in improving software quality and productivity, highlighting its strategic value.

  • Definition of a Program (N. Wirth, 1975)

    • Input data → Program (algorithm) → Output Data: This illustrates the fundamental process of a program taking input data, processing it through an algorithm, and producing output data.

    • Programs = Algorithms + Data structures: This equation emphasizes that a program is composed of algorithms (the steps to solve a problem) and data structures (how the data is organized and managed).

    • This definition emphasizes that a program fundamentally consists of algorithms (the steps to solve a problem) combined with data structures (how data is organized and managed). It's a concise way to describe the essence of any software program.

  • Definition of Programming

    • Human activity of writing programs for a computer system: Programming is the act of creating instructions for a computer to execute.

    • Programs need to be transformed into executable specifications that can be interpreted by a computer to solve a problem: The code written by humans must be translated into a format that a computer can understand and execute.

    • Executable specification = a sequence of computations that can be executed by a microprocessor: An executable specification is a detailed set of instructions that a computer's processor can follow.

    • Programming involves creating detailed instructions that a computer can follow to perform specific tasks, transforming human-readable code into machine-executable steps. This process ensures that the computer can perform the intended functions.

  • Problems of Programming

    • Labor-intensive task: Writing software often requires a significant amount of time and effort.

    • Manual repetitive coding: Many tasks involve writing similar code multiple times, which is inefficient.

    • Inefficient typing system: Traditional typing systems can be rigid and error-prone, slowing down development.

    • Difficult to adapt and reuse: Code may not be easily modified for new situations or used in different projects.

    • Code duplication: Similar blocks of code are often repeated throughout a project, leading to maintenance issues.

    • Difficult to change and maintain: Making updates to code can be challenging and may introduce new bugs.

    • Example: multiple abs() functions for different types in Java's Math package. This illustrates the need for generic programming to avoid code duplication.

    • Traditional programming can be time-consuming and prone to errors due to repetitive manual coding, rigid typing systems, and difficulties in adapting and maintaining code. These challenges highlight the need for more advanced programming techniques.

  • Generic Programming

    • Provides less manual effort, no repetitive code, efficient typing system, reusable code, no code duplication, and easy maintenance: Generic programming addresses many of the issues in traditional programming.

    • Leads to more flexible, reusable, and maintainable programs, resulting in higher productivity and better software quality: The benefits of generic programming are significant, improving both the development process and the end product.

    • Generic programming enhances software development by reducing manual effort, promoting code reuse, and improving overall software maintainability and quality. It's a more efficient and effective approach.

  • Explanation of Metaprogramming

    • Meta (from Greek meta- μετά- meaning "after" or "beyond") means more comprehensive or transcending (being “above”) something: The term "meta" indicates a higher level of abstraction.

    • Meta-programming is a higher-level programming aiming to extend programming by constructing programs automatically: Metaprogramming involves writing code that generates or manipulates other code.

    • Meta-program – a higher-level program: A metaprogram is a program that operates on other programs.

    • Metaprogramming is a sophisticated approach that transcends traditional programming by enabling the automatic creation of programs, thereby extending the capabilities of software development. It allows for automating tasks and creating more flexible software.

  • Definition of Meta-Programming

    • Creating programs that can:

    • Examine its own structure (= program reflection): Allows the program to inspect its own code, attributes, and states at runtime, enabling dynamic analysis and modification.

    • Create (generate) other programs (= program generation): Automatically produce new programs or code segments based on predefined rules or templates, facilitating rapid development and customization.

    • Specify other programs (= program generalization): Define general-purpose programs that can be adapted or configured to solve specific problems, promoting code reuse and reducing redundancy.

    • Transform (extend, insert, delete, adapt) other programs (= program transformation): Modify existing programs by adding new features, removing obsolete code, or adapting them to new environments, ensuring long-term maintainability and compatibility.

    • Solve some specific tasks better (= program specialization): Tailor programs to perform specific tasks more efficiently or effectively than general-purpose solutions, optimizing performance and resource utilization.

    • Metaprogramming involves creating programs with advanced capabilities such as self-examination, code generation, program specification, transformation, and specialization to improve efficiency and effectiveness. These capabilities enable more dynamic, flexible, and optimized software solutions.

  • Metaprogram vs Program

    • Program: sequence of actions (algorithm) to derive output data from input data: A traditional program takes input, processes it, and produces output.

    • Metaprogram: generalization of program, a sequence of actions to derive a new program from given inputs (parameters): A metaprogram takes parameters, and its output is another program.

    • A metaprogram is a generalized program that derives new programs from given inputs, extending the functionality of regular programs by automating program creation. It automates the creation of specialized programs.

  • Why Metaprograms Are Needed

    • Deal with growing software complexity: As software systems become larger and more intricate, metaprogramming can help manage the complexity.

    • Move programming towards higher abstraction levels: Metaprogramming enables more abstract and expressive code, reducing the amount of boilerplate code.

    • Achieve higher productivity in software development: By automating code generation and manipulation, metaprogramming can significantly increase development speed.

    • Generate programs (or parts thereof) automatically: This automation reduces the need for manual coding, saving time and effort.

    • Metaprograms are essential for managing increasing software complexity, elevating abstraction levels, boosting development productivity, and automating program generation. They provide tools to create more manageable and efficient software.

  • Origins of Metaprogramming

    • In 1959, the IBM 709 introduced programmer macros as a sequence of computing instructions available in a single program statement: This was an early form of metaprogramming.

    • Macro-instructions = macros: These were shorthand notations for sequences of instructions.

    • A single computer instruction that initiates a set of instructions to perform a specific task: Macros allowed programmers to define reusable blocks of code.

    • Allow for tailoring and combining of source code sections: Macros could be customized and combined to perform various tasks.

    • Metaprogramming originated with IBM 709 in 1959, which introduced macros as sequences of computing instructions that could be tailored and combined to perform specific tasks. This was a significant step in the evolution of programming techniques.

  • How Macros Work

    • A macro is a directive that expands into a set of instructions when compiled or preprocessed: Macros are replaced with their defined code during the compilation process.

    • It serves as a shorthand notation, replacing the macro call in the source code with the actual sequence of instructions it represents: This simplifies the code and reduces redundancy.

    • The primary goal of macros is to Save time, Reduce errors, Improve code readability: Macros help make code more efficient and easier to understand.

    • Early Metaprogramming Capabilities Enabled automated code manipulation and generation: Macros were an early form of automating code-related tasks.

    • Macros function by expanding into a set of instructions during compilation or preprocessing, serving as shorthand notations that automate code manipulation and generation, thereby saving time, reducing errors, and improving code readability. They streamline the development process.

  • C Preprocessing Macros

    • Macros do not compute, they expand code: C macros perform text substitution rather than computation.

    • pred(2) → ((2) -1): This demonstrates how a macro replaces text.

    • pred(y+2) → ((y+2) -1): Another example of text substitution.

    • pred(f(5)) → ((f(5))-1): This shows that macros don't evaluate expressions.

    • Example of code modification: Macros are used to modify code before compilation.

    • C preprocessing macros expand code without performing computations, allowing for efficient code modification and generation during the preprocessing stage. They are a simple but powerful tool for code manipulation.

  • Macro #define

    • Symbolic constants, constants represented as symbols: Symbolic constants are named values that can be used throughout the code.

    • Format #define ident replacement: This is the basic syntax for defining a macro.

    • Replace identifier with a string of text: The identifier is replaced with the specified text.

    • #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ): An example of a macro to calculate the area of a circle.

    • area = CIRCLE_AREA( 4 ); becomes area = ( 3.14159 * ( 4 ) * ( 4 ) ): This shows how the macro is expanded during preprocessing.

    • area = CIRCLE_AREA( c + 2 ); becomes area = 3.14159 * (c + 2) * (c + 2): Another expansion example.

    • The #define macro in C allows you to define symbolic constants and replace identifiers with specified text, facilitating code customization and readability. It's a fundamental tool for C programming.

  • '#if' Macro for Conditional Compilation

    • Structure similar to if: The #if macro works like a conditional statement.

    • Do not "comment out" code, instead, use #if 0 … #endif. To enable code, change 0 to 1: This is a technique for including or excluding code during compilation.

    • The #if macro in C is used for conditional compilation, enabling or disabling blocks of code based on specified conditions without commenting out code. It allows for creating different versions of the code.

  • #if Macro for Program Specialization

    • #if and #endif directives control conditional compilation: These directives determine which parts of the code are compiled.

    • Only one version (instance) of a program will be compiled on-demand: Based on the conditions, a specific version of the code is generated.

    • A case of program specialization: This technique is used to create specialized versions of programs.

    • The #if and #endif directives in C control conditional compilation, allowing only one version of a program to be compiled based on specified conditions, thus enabling program specialization. It's a powerful tool for creating optimized and customized software.

  • Language and Metalanguage: Different Levels of Abstraction

    • Metalanguage: A language used to describe other languages.

    • language: The language being described or manipulated.

    • Languages and metalanguages represent different levels of abstraction, where metalanguages are used to describe or analyze other languages. This distinction is fundamental in the study of programming languages and metaprogramming.

  • Metalanguage: Definition

    • A metalanguage is ‘any language or symbolic system used to discuss, describe, or analyze another language or symbolic system is a metalanguage’ (Batory): This is a formal definition of a metalanguage.

    • A program written in a metalanguage is a metaprogram: Metaprograms operate on other programs using a metalanguage.

    • Metaprogram describes the syntax of target program. Semantics (meaning) is implemented using target language: The metaprogram defines the structure, while the target language implements the functionality.

    • A metalanguage is a symbolic system used to describe or analyze another language, with metaprograms written in metalanguages to define the syntax of target programs while implementing semantics in the target language. It's crucial for advanced programming techniques.

  • Metaprogramming Use Cases

    • Code Generation: Automatically creating code based on templates or specifications.

    • Generic Programming: Writing code that works with multiple data types without specifying them explicitly.

    • Reflection & Introspection: Allowing a program to examine and modify its own structure and behavior at runtime.

    • Macros & Preprocessing: Using macros to perform code transformations before compilation.

    • Aspect-Oriented Programming (AOP): Separating cross-cutting concerns to increase modularity.

    • Dynamic Proxies & Dependency Injection: Creating dynamic objects and managing dependencies at runtime.

    • Domain-Specific Languages (DSLs): Designing specialized languages for specific tasks.

    • Compile-Time Computation: Performing computations during compilation to optimize code.

    • Software Product Lines & Specialization: Creating families of related software products automatically.

    • Metaprogramming has various use cases including code generation, generic programming, reflection, macros, aspect-oriented programming, dynamic proxies, domain-specific languages, compile-time computation, and software product lines. These applications demonstrate its versatility and power.

  • Program Generation with Unix Shell

    • Metaprogramming allows automatic generation of repetitive code, reducing manual effort and minimizing errors: This is a key benefit of metaprogramming.

    • Example: Unix shell language Creation of shell program as strings printed to file. A case of program generation: Unix shell scripts can generate other shell scripts.

    • With metaprogramming, repetitive code can be automatically generated, which reduces manual effort and minimizes errors, as demonstrated by Unix shell languages creating shell programs by printing strings to a file. This is a practical example of code generation.

  • Generic Programming in Java

    • Algorithms are written in terms of types to-be-specified-later that are instantiated when needed for specific types provided as parameters: This is the essence of generic programming.

    • Types are abstracted from concrete algorithms and data structures and formalized as concepts. Example: Generics in Java: Java generics allow writing code that works with any type.

    • Generic programming in Java involves writing algorithms in terms of types that are specified later, abstracting types from concrete algorithms and data structures, and formalizing them as concepts through generics. It increases code reusability and type safety.

  • Generic Types

    • Supported by Java: Java provides built-in support for generic types.

    • A generic type is a generic class or interface that is parameterized over types: This allows creating classes that work with different types.

    • A generic class is defined with the following format:

    • class name { /* … */ }

    • Example:

    • public class Box { // T stands for "Type"
      private T t;
      public void set(T t) { this.t = t; }
      public T get() { return t; }
      }

    • Generic types in Java, supported by generic classes and interfaces, are parameterized over types and allow type abstraction in class definitions. This example illustrates how to define and use generic types in Java.

  • Generative Programming in C++

    • Programs written "to manufacture software components in an automated way" Enables products to be generated automatically from specifications. Example: STL library in C++: The STL uses templates extensively to generate code.

    • Generative programming in C++ involves writing programs that automatically manufacture software components from specifications, exemplified by the STL library. It leverages templates for code generation.

  • Type Generalization in C++

    • C++ Templates: a metaprogramming technique that allow writing code without specifying the type of data used Template in C++ defines a generic class: Templates are a powerful feature of C++.

    • For example, a List class template defines a class that can hold the objects of any type A case of program generalization: This is a practical example of type generalization.

    • C++ templates are a metaprogramming technique that allows writing code without specifying data types, defining generic classes like the List class template that can hold objects of any type, exemplifying program generalization. They provide a way to write code that is independent of specific data types.

  • Reflection

    • Reflection is the ability of a program to examine, introspect, and modify its own structure and behavior: This allows for dynamic code analysis and manipulation.

    • A language supporting reflection provides features available at runtime: Modify source-code constructions (such as code blocks, classes, methods, etc.) at runtime: Reflection enables runtime code modifications.

    • Object foo = Class.forName("complete.classpath.and.Foo").newInstance();: An example of creating an object using reflection in Java.

    • Reflection enables a program to examine, introspect, and modify its own structure and behavior at runtime, allowing for dynamic code manipulation. It's a powerful tool for creating flexible and adaptable software.

  • Examples of Metaprogramming: Reflection

    • Python3: metaclasses Allow to create classes and add (or remove) new fields and methods at run-time A case of program modification: Metaclasses enable dynamic class modifications.

    • In Python 3, metaclasses allow creating classes and modifying their structure by adding or removing fields and methods at runtime, illustrating program modification. They provide a way to customize class creation dynamically.

  • Metaclasses

    • Supported by Python 3: Metaclasses are a key feature of Python.

    • - A metaclass is a (higher-level) class whose instances are classes. A metaclass defines the properties and behavior of classes and their instances: This is the definition of a metaclass.

    • automatically adding new methods automatic property creation: Metaclasses automate the process of adding methods and properties to classes.

    • Metaclasses in Python 3 are higher-level classes that define the properties and behavior of other classes and their instances, enabling automatic method and property creation. They provide a way to control the creation and behavior of classes.

  • Aspect-Oriented Programming

    • Aims to increase modularity by allowing the separation of cross-cutting concerns.-: AOP improves code organization by separating concerns.

    • A technique for building common, reusable routines that can be applied application-wide: AOP allows creating reusable components.

    • An aspect is a common feature that's typically scattered across methods, classes,: Aspects encapsulate cross-cutting concerns.

    • Aspect-oriented programming (AOP) enhances modularity by separating cross-cutting concerns, allowing for the creation of reusable routines applied across methods and classes. It simplifies the management of complex systems.

  • Self-Modifying Code

    • Used in frameworks to inject dependencies and create dynamic proxies for modular programming: Self-modifying code is used in advanced frameworks.

    • Self-modifying code is used in frameworks to inject dependencies and create dynamic proxies for modular programming, enhancing flexibility and modularity. It allows for dynamic customization of program behavior.

  • Creating Domain-Specific Languages

    • Facilitates the creation of specialized mini-languages within a general-purpose language. Example: SQL embedded in Python (via ORMs) or LaTeX for document typesetting: DSLs simplify specific tasks.

    • Creating domain-specific languages (DSLs) facilitates the development of specialized mini-languages within general-purpose languages, such as SQL embedded in Python or LaTeX for document typesetting. They provide a more natural and efficient way to express specific problems.

  • Meta-objects

    • Meta-object is an object that manipulates, creates, describes, or implements base (target) objects May manipulate the base object's type, interface, class, methods, attributes, parse tree, etc: Meta-objects operate on other objects.

    • Typical functions of a meta-object include:

    • Create or delete a new class

    • Supported by AspectJ: AspectJ supports meta-objects.

    • Meta-objects manipulate, create, describe, or implement base objects, modifying the base object's type, interface, class, methods, attributes, or parse tree, and are supported by AspectJ. They provide a fine-grained control over object behavior.

  • Example of Meta-Object in AspectJ

    • public class PaymentService {\
      public void processPayment() {\
      System.out.println("Processing payment…");\
      }
      public static void main(String[] args) {\
      new PaymentService().processPayment();\
      }
      }
      @Aspect\
      public class Logging Aspect {\
      @Before("execution (void PaymentService.processPayment())")\
      public void logBefore() {\
      System.out.println("Logging: Payment process started.");\
      }
      }

  • Higher Order Functions

    • Takes one or more functions as arguments and/or returns a function as its result: Higher-order functions treat functions as data.

    • Supported by Java (from 1.8), C++ (from C++ 11), JavaScript, Python, etc: Many modern languages support higher-order functions.

    • Useful for code modularity, code reusability, and reduced code duplication: Higher-order functions improve code quality.

    • Higher-order functions take one or more functions as arguments or return a function as their result, supported by languages like Java, C++, JavaScript, and Python, enhancing code modularity, reusability, and reducing duplication. They enable more flexible and expressive code.

  • Example of Higher Order Function: Python Decorators

    • python def add_two(func): def wrapper (*args, **kwargs): result = func(*args, **kwargs) return result + 2 return wrapper @add_two def square(x): return x ** 2 print(square(5)) # prints 27 (5**2 + 2)

  • Example of Higher Order Function in JavaScript

    • javascript Array.prototype.map = function (callback) { var mappedArray = []; for (var i = 0; i < this.length; i++) { var mappedValue = callback(this[i], i, this); mappedArray.push(mappedValue); } return mappedArray; }; var originalArray = [1, 2, 3, 4, 5]; var mappedArray = originalArray.map(function(element) { return element * 2; }); console.log(mappedArray); // [2, 4, 6, 8, 10]

  • JIT Compilation as Metaprogramming

    • Just-In-Time (JIT) compilation modifies execution dynamically: JIT compilation optimizes code during runtime.

    • Example: Python’s PyPy, Java’s HotSpot, and LLVM optimizations: These are examples of JIT compilation engines.

    • PyPy is an alternative implementation of Python that is optimized for speed and efficiency through Just-In-Time (JIT) compilation.: PyPy uses JIT extensively.

    • Just-In-Time (JIT) compilation modifies execution dynamically, as seen in Python’s PyPy, Java’s HotSpot, and LLVM optimizations, with PyPy optimizing Python for speed and efficiency through JIT compilation. It enhances performance by adapting the code to the runtime environment.

  • Metadata

    • Introduced by D. Griffel and S. McIntosh in 1967: Metadata has a long history in computer science.

    • Descriptive metadata:

    • For search, identification: Descriptive metadata provides information about the data.

    • Structural metadata:

    • How parts are related: Structural metadata describes the organization of the data.

    • expressed in markup programming languages such as XML: XML is commonly used to represent metadata.

    • Metadata, introduced by D. Griffel and S. McIntosh in 1967, includes descriptive metadata for search and identification, and structural metadata indicating how parts are related, often expressed in markup languages like XML. It provides a way to manage and understand complex data.

  • Markup Languages

    • A system for annotating a document: Markup languages add information to documents.

    • separation of Content and Presentation Create structured documents Standards and Accessibility Extensibility: Markup languages promote structured and accessible documents.

    • Markup languages annotate documents, separating content from presentation to create structured, standardized, accessible, and extensible documents. They facilitate the creation of well-organized and easily maintainable content.

  • Latex

    • A high-level, descriptive markup language that handles typesetting and rendering LaTeX. Separating presentation from content – two levels of abstraction metalanguage language: LaTeX simplifies document creation.

    • LaTeX is a high-level markup language that handles typesetting and rendering, separating presentation from content to create two levels of abstraction. It is widely used for scientific and technical documentation.

  • Hypertext Markup Language (HTML)

    • Standard markup language for displaying documents in a web browser Structural markup indicates the purpose of text (semantics) Presentational markup indicates the appearance of text, regardless of its purpose: HTML is the foundation of the web.

    • Hypertext Markup Language (HTML) is the standard markup language for displaying documents in a web browser, with structural markup indicating the purpose of text and presentational markup indicating appearance. It provides a structured way to create web content.

  • Extensible Markup Language (XML)

    • Markup language that separates data from presentation: XML is designed for data storage and exchange.

    • Extensible Markup Language (XML) is a markup language that separates data from presentation, allowing for structured data storage and exchange. It is widely used for data serialization and configuration.

  • Metaprogramming in Security (Code Injection)

    • Metaprogramming can introduce security vulnerabilities Example: Code injection attacks and mitigation strategies: Metaprogramming can create security risks.

    • Metaprogramming can introduce security vulnerabilities, such as code injection attacks, requiring careful mitigation strategies. It is important to implement security measures when using metaprogramming techniques.

  • Metaprogramming in AI & Machine Learning

    • Enables dynamic model generation, automatic differentiation, and adaptive computation graphs. Allows models to be modified at runtime based on data and training constraints.: Metaprogramming improves AI models.

    • Metaprogramming in AI and machine learning enables dynamic model generation, automatic differentiation, and adaptive computation graphs, allowing models to be modified at runtime based on data and training constraints. It facilitates the creation of more flexible and adaptive AI systems.

  • Meta-modelling

    • A metamodel is a model of a model: Meta-modeling involves creating models of models.

    • Definition of constructs and rules (i.e., syntax) needed for creating models. Metamodeling is the process of creating (generating) metamodels Model-Driven Engineering (MDE): Meta-modeling is used in MDE.

    • Meta-modeling involves creating metamodels, which are models of models, to define the constructs and rules needed for creating models in Model-Driven Engineering (MDE). It provides a way to formalize and automate the modeling process.

  • Software Factories and Product Lines

    • Adopted by Toshiba (Japan): Toshiba has used software factories.

    • Software factories and product lines, adopted by companies like Toshiba in Japan, utilize metaprogramming techniques for automated software production. They enable the creation of families of related software products more efficiently.

  • Metaprogramming in Modern Software Development

    • Metaprogramming enables low-code/no-code platforms Example: Scaffolding in Django, Angular, and Rails: Metaprogramming drives low-code platforms.

    • Metaprogramming in modern software development enables low-code/no-code platforms, such as scaffolding in Django, Angular, and Rails, to accelerate development processes. It allows developers to create applications with minimal manual coding.

  • Summary

    • Many cases of metaprogramming

    • Program transformation Program generation- Program generalization Program specialization

    • Software product lines / software factories

    • Metaprogramming includes numerous cases such as program transformation, program generation, program generalization, program specialization, and is utilized in software product lines and software factories. These applications highlight its broad applicability.

  • C++ Template Metaprogramming: Function Templates

    • Template metaprogramming is technique in which templates written in a template language are used by a compiler to generate intermediate code at compile-time in a specific programming language (such as C++): Template metaprogramming occurs at compile time.

    • C++ templates are written using a subset of C++ language Template is a blueprint for creating a generic class or a function.: Templates are a key part of C++.

    • Template metaprogramming in C++ involves using templates written in a template language to generate intermediate code at compile-time in a specific programming language like C++, with C++ templates serving as blueprints for creating generic classes or functions. It allows for creating highly optimized code.

  • Templates define generic entities (classes or functions) and describe how to generate specific C++ code Template functions and data structures (classes, types) are parameterized by types and values

    • Templates are used to create generic code that works with different data types.

  • What is Instantiation?

    • Template defines a generic solution, that is generic program code with some parameters

    • -Instantiation Workflow Template Definition Compiler Encounters the Template Use Template Instantiation Compilation of Instantiated Template

    • Instantiation involves defining a generic solution with a template, triggering the instantiation workflow where the compiler encounters the template, uses it to instantiate code, and compiles the instantiated template. It is the process of creating specific code from a general template.

  • Instance in Metaprogramming & Object-Oriented Programming

    • Differences: Creation: Class instances are created dynamically during the execution of the program Template instances are created at compile-time Lifetime: Class instances exist at runtime Template instances exist statically as blueprints until compiler instantiates them.

    • Instances in metaprogramming differ from those in object-oriented programming in creation and lifetime: class instances are created dynamically at runtime, while template instances are created at compile-time and exist statically as blueprints. This distinction is important for understanding the behavior of code.

  • Templates With Multiple Parameters

    • The number of template parameters must match the number of function arguments Multiple templates would not be legalVariable with Type2 is not in the parameter list

    • With templates that have multiple parameters, the number of template parameters must match the number of function arguments, and each parameter must be included in the parameter list. This ensures that the template can be properly instantiated.

  • Template FunctioTemplate Specialization

    • Defines specific behavior for a specific type by providing override of the function template for that type.

    • A template specialization changes the behaviour of the template for a specific type.

    • Template function specialization defines specific behavior for a specific type by overriding the function template, allowing for customized behavior based on the type used. It allows for creating optimized versions of the code for specific data types.

  • Overloading templates can provide custom behavior for specific types.

    • Template overloading enables different behavior based on the types used with the template.

  • Function Templates vs Macros. Using Function Templates Instead of Macros?

    • Function Templates Create generic functions that can work with different types of data without having to write separate functions for each type.

    • Create generic code that can work with different types of data.Result: more efficient and maintainable code

    • Function templates create generic functions that work with different types of data without requiring separate functions for each type, resulting in more efficient and maintainable code compared to macros. Templates provide better type safety and code organization.

  • Function Template Overloading: The number of template parameters must match the number of function arguments Each type parameter must be usedTemplates With Multiple Parameters

    • Create generic functions that can work with different types of data without having to write separate functions for each type.

    • Function template overloading requires the number of template parameters to match the number of function arguments, and each type parameter must be used, which allows creating generic functions that work with different data types. It enables more flexible and type-safe code.

  • Function Template SpecializationTemplates can can provide default values for template parametersConstraints for Function Templates

    • Create generic functions that can work with different types of data without having to write separate functions for each type.

    • Function template specialization allows templates to provide default values for template parameters, creating generic functions that work with different types of data without needing separate functions for each type. It simplifies the use of templates and provides more flexibility.

  • Class Member Function Templates

    • Classes also can have function templates

    • Classes can also have function templates, allowing for generic operations within class structures. It allows for creating highly generic and reusable code.

  • Generates generic classes into which specific data types can be plugged in to produce new classes: public: T x; U y;

    • This allows for creating highly flexible and reusable classes.

  • Auto template parameters Auto return typeHow to define return value type

    • These features simplify the use of templates by allowing the compiler to deduce types automatically.

  • Template Specialization template f( T ); template<> void f( int );

    • This illustrates how to specialize a template for a specific type.

  • Variable templates (since C++1414Define a variable of undefined type

    • Variable templates allow defining generic variables.

  • Trait classes provide a set of methods that implement behaviour to a classTraits for Container classes Traits: advantages and disadvantagesMixins with its derived classes

    • Trait classes are used to add behavior to classes.

  • Mixin:Mixinsmall functionality slice intended to be composed with

    • Mixins provide a way to compose classes with small pieces of functionality.

  • Template of Templates used when you want to write code that works with any container-like template classTemplates for Meta functions,

    • These techniques allow for writing highly