Dynamic Polymorphism with Code Injection and Metaclasses

Total Page:16

File Type:pdf, Size:1020Kb

Dynamic Polymorphism with Code Injection and Metaclasses 1 (they/them), @TartanLlama C++ Developer Advocate at Microsoft 2 Dynamic Polymorphism 3 Polymorphism: The provision of a single interface to entities of different types 4 Dynamic Static Polymorphism Polymorphism 5 Dynamic Static Polymorphism Polymorphism Run-time Compile-time 6 Dynamic Static Polymorphism Polymorphism Run-time Compile-time Different behaviour based on Different behaviour based on dynamic type static type 7 Dynamic Static Polymorphism Polymorphism Run-time Compile-time Different behaviour based on Different behaviour based on dynamic type static type Typically implemented with Typically implemented with inheritance overloading and templates 8 9 10 Problems with inheritance 11 Often requires dynamic allocation Dynamic Allocation 12 struct base{}; struct a : base{}; struct b : base{}; base make_base(); std::vector<base> v; Dynamic Allocation 13 struct base{}; struct a : base{}; struct b : base{}; std::unique_ptr<base> make_base(); std::vector<std::unique_ptr<base>> v; Problems with inheritance 14 Often requires dynamic allocation Ownership and nullability considerations Problems with inheritance 15 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes Intrusive Polymorphism 16 namespace mylib { struct base { virtual void do_thing(); }; } namespace otherlib { struct x { virtual void do_thing(); }; } Intrusive Polymorphism 17 namespace mylib { struct base { virtual void do_thing(); }; } namespace otherlib { struct x { virtual void do_thing(); }; } mylib::base* b = new otherlib::x; Problems with inheritance 18 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Problems with inheritance 19 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers 20 struct animal { virtual ~animal(); virtual void speak() = 0; }; struct cat : animal { void speak() override; }; struct dog : animal { void speak() override; }; 21 struct animal { virtual ~animal(); Felix virtual void speak() = 0; }; struct cat : animal { void speak() override; }; struct dog : animal { void speak() override; }; 22 struct animal { virtual ~animal(); Felix virtual void speak() = 0; }; struct cat : animal { void speak() override; }; vtable for cat struct dog : animal { void speak() override; }; 23 struct animal { virtual ~animal(); Felix virtual void speak() = 0; }; struct cat : animal { void speak() override; }; vtable for cat struct dog : animal { void speak() override; }; struct animal { 24 // magic }; struct cat { void speak(); }; struct dog { void speak(); }; struct animal { 25 // magic }; int main() { animal c = cat{}; struct cat { c.speak(); void speak(); }; animal d = dog{}; d.speak(); struct dog { } void speak(); }; Hand-written virtual functions 26 Declare vtable for the abstract interface Define vtable for a concrete type Capture the vtable pointers on construction Forward calls through the vtable 27 struct animal { virtual ~animal(); virtual void speak() = 0; }; struct cat : animal { void speak() override; }; struct dog : animal { void speak() override; }; Hand-written virtual functions 28 Declare vtable for the abstract interface Define vtable for a concrete type Capture the vtable pointers on construction Forward calls through the vtable 29 struct vtable { void (*speak)(void* ptr); void (*destroy_)(void* ptr); }; Hand-written virtual functions 30 Declare vtable for the abstract interface Define vtable for a concrete type Capture the vtable pointers on construction Forward calls through the vtable 31 template<class Concrete> constexpr vtable vtable_for { // function which calls speak // function which deletes object }; 32 template<class Concrete> constexpr vtable vtable_for { [] (void* ptr) { static_cast<Concrete*>(ptr)->speak(); }, [] (void* ptr) { delete static_cast<Concrete*>(ptr); } }; Hand-written virtual functions 33 Declare vtable for the abstract interface Define vtable for a concrete type Capture the vtable pointers on construction Forward calls through the vtable 34 struct animal { void* concrete_; vtable const* vtable_; }; 35 struct animal { void* concrete_; vtable const* vtable_; template<class T> animal(T const& t) : concrete_(new T(t)), vtable_(&vtable_for<T>) {} }; Hand-written virtual functions 36 Declare vtable for the abstract interface Define vtable for a concrete type Capture the vtable pointers on construction Forward calls through the vtable 37 struct animal { // ... void speak() { vtable_->speak(t_); } ~animal() { vtable_->destroy_(t_); } }; struct cat { 38 void speak(); }; struct dog { void speak(); }; struct cat { 39 void speak(); }; struct dog { void speak(); }; int main() { animal c = cat{}; c.speak(); animal d = dog{}; d.speak(); } Problems with inheritance 40 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers Problems with inheritance 41 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers Problems with inheritance 42 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers struct vtable { 43 void (*speak)(void* ptr); void (*destroy_)(void* ptr); void* (*clone_)(void* ptr); void* (*move_clone_)(void* ptr); }; struct vtable { 44 void (*speak)(void* ptr); void (*destroy_)(void* ptr); void* (*clone_)(void* ptr); void* (*move_clone_)(void* ptr); }; template<class T> constexpr vtable vtable_for { [] (void* ptr) { static_cast<T*>(ptr)->speak(); }, [] (void* ptr) { delete static_cast<T*>(ptr); }, [] (void* ptr) -> void* { return new T(*static_cast<T*>(ptr)); }, [] (void* ptr) -> void* { return new T(std::move(*static_cast<T*>(ptr))); } }; struct animal { 45 //... animal(animal const& rhs) : t_(rhs.vtable_->clone_(rhs.t_)), vtable_(rhs.vtable_) {} animal(animal&& rhs) : t_(rhs.vtable_->move_clone_(rhs.t_)), vtable_(rhs.vtable_) {} }; int main() { 46 animal a = cat{}; a.speak(); a = dog{}; a.speak(); animal b = a; b.speak(); } int main() { 47 std::vector<animal> animals { cat{}, dog{} }; for (auto&& a : animals) { a.speak(); } } Problems with inheritance 48 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers Problems with inheritance 49 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers Problems with inheritance 50 Often requires dynamic allocation Ownership and nullability considerations Intrusive: requires modifying child classes No more value semantics Changes semantics for algorithms and containers struct vtable { void (*speak)(void* ptr); void (*destroy_)(void* ptr); void* (*clone_)(void* ptr); void* (*move_clone_)(void* ptr); 51 }; template<class T> constexpr vtable vtable_for { [] (void* ptr) { static_cast<T*>(ptr)->speak(); }, [] (void* ptr) { delete static_cast<T*>(ptr); }, [] (void* ptr) -> void* { return new T(*static_cast<T*>(ptr)); }, [] (void* ptr) -> void* { return new T(std::move(*static_cast<T*>(ptr))); } }; struct animal { void* t_; vtable const* vtable_; void speak() { vtable_->speak(t_); } ~animal() { vtable_->destroy_(t_); } template<class T> animal(T const& t) : t_(new T(t)), vtable_(&vtable_for<T>) {} animal(animal const& rhs) : t_(rhs.vtable_->clone_(rhs.t_)), vtable_(rhs.vtable_) {} animal(animal&& rhs) : t_(rhs.vtable_->move_clone_(rhs.t_)), vtable_(rhs.vtable_) {} animal& operator=(animal const& rhs) { t_ = rhs.vtable_->clone_(rhs.t_); vtable_ = rhs.vtable_; return *this; } animal& operator=(animal&& rhs) { t_ = rhs.vtable_->move_clone_(rhs.t_); vtable_ = rhs.vtable_; return *this; } }; 52 Static Reflection 53 Reflection: The ability of a program to introspect its own structure 54 Static Reflection: The ability of a program to introspect its own structure at compile-time 55 std::is_array<T> 56 std::is_same<T, U> 57 Enum to string? Iterate over members? 58 59 template<Enum T> constexpr std::string to_string(T value) { } 60 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { } } 61 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { } } 62 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { } } 63 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { if (exprid(e) == value) { } } } 64 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { if (exprid(e) == value) { } } } 65 template<Enum T> constexpr std::string to_string(T value) { for constexpr (auto e : std::meta::members_of(reflexpr(T)) { if (exprid(e) == value) { return std::meta::name_of(e); } } } 66 template<Enum T> constexpr std::string to_string(T value) { for constexpr
Recommended publications
  • J1939 Data Mapping Explained
    J1939 Data Mapping Explained Part No. BW2031 Revision: 1.05 May 18, 2018 Pyramid Solutions, Inc. 30200 Telegraph Road, Suite 440 Bingham Farms, MI 48025 www.pyramidsolutions.com | P: 248.549.1200 | F: 248.549.1400 © Pyramid Solutions 1 PUB-BW4031-001 Table of Contents Overview ......................................................................................................................... 2 J1939 Message Terminology ............................................................................................ 2 J1939 PGN Message Definitions ....................................................................................... 3 PGN and Parameter Documentation Examples ........................................................................ 3 J1939 Specification Example ........................................................................................................ 3 Parameter Table Example ............................................................................................................ 5 Determining the BridgeWay Data Table Layout ................................................................ 6 Data Table Layout for Modbus RTU and Modbus TCP (Big Endian) ........................................... 6 Data Table Layout for EtherNet/IP (Little Endian) .................................................................... 7 Configuring the BridgeWay I/O Mapping ......................................................................... 8 Configuration Attributes ........................................................................................................
    [Show full text]
  • Advanced Software Engineering with C++ Templates Lecture 4: Separate Compilation and Templates III
    Advanced Software Engineering with C++ Templates Lecture 4: Separate Compilation and Templates III Thomas Gschwind <thgatzurichdotibmdotcom> Agenda . Separate Compilation • Introduction (C++ versus Java) • Variables • Routines (Functions & Operators) • Types (Structures, Classes) • Makefiles . Templates III • Design and Implementation (C++ versus Java versus C#) • “Dynamic” Static Algorithm Selection • Binders Th. Gschwind. Fortgeschrittene Programmierung in C++. 2 Separate Compilation . Why? • Having only one source file is unrealistic • Break the code up into its logical structure • Reduction of compile time - Only changed parts need to be recompiled . How? • Use multiple source files • Need to know what information about functions and variables “used” from other files Th. Gschwind. Fortgeschrittene Programmierung in C++. 3 Separate Compilation in Java . Each Java file is compiled into a class file . If a Java class invokes a method of another class, the compiler consults that other class file to • Determine whether the class provides the requested method • Determine whether a class file implements a given interface • etc. • Hence, the .class file contains the entire interface . That’s why in Java, the compiler needs the class path . Finally, all class files are loaded by the Java Virtual Machine (and “linked”) . Java source code can be relatively well reconstructed from .class file (see Java Decompiler: jd, jad) Th. Gschwind. Fortgeschrittene Programmierung in C++. 4 Some Java Trivia . Let us write Hello World in Java . In order to simplify the reconfiguration (e.g., translation) • Put all the constants into one Java file • Put the complex application code into another public class Const { public static final String msg="Hello World!"; } public class Cool { public static void main(String[] args) { System.out.println(Const.msg); } } Th.
    [Show full text]
  • P2356R0 Date 2021-04-09 Reply-To Matus Chochlik [email protected] Audience SG7 Overview Details
    Overview Details Implementing Factory builder on top of P2320 Document Number P2356R0 Date 2021-04-09 Reply-to Matus Chochlik [email protected] Audience SG7 Overview Details The goal (Semi-)automate the implementation of the Factory design pattern Overview Details What is meant by \Factory" here? • Class that constructs instances of a \Product" type. • From some external representation: • XML, • JSON, • YAML, • a GUI, • a scripting language, • a relational database, • ... Overview Details Factory builder • Framework combining the following parts • Meta-data • obtained from reflection. • Traits • units of code that handle various stages of construction, • specific to a particular external representation, • provided by user. Overview Details Factory builder • Used meta-data • type name strings, • list of meta-objects reflecting constructors, • list of meta-objects reflecting constructor parameters, • parameter type, • parameter name, • ... Overview Details Factory builder • Units handling the stages of construction • selecting the \best" constructor, • invoking the selected constructor, • conversion of parameter values from the external representation, • may recursively use factories for composite parameter types. Overview Details Used reflection features • ^T • [: :]1 • meta::name_of • meta::type_of • meta::members_of • meta::is_constructor • meta::is_default_constructor • meta::is_move_constructor • meta::is_copy_constructor • meta::parameters_of • size(Range) • range iterators 1to get back the reflected type Overview Details Reflection review • The good2 • How extensive and powerful the API is • The bad • Didn't find much3 • The ugly • Some of the syntax4 2great actually! 3some details follow 4but then this is a matter of personal preference Overview Details What is missing • The ability to easily unpack meta-objects from a range into a template, without un-reflecting them. • I used the following workaround + make_index_sequence: template <typename Iterator > consteval auto advance(Iterator it, size_t n) { while (n-- > 0) { ++ it; } return it; } • Details follow.
    [Show full text]
  • Metaclasses: Generative C++
    Metaclasses: Generative C++ Document Number: P0707 R3 Date: 2018-02-11 Reply-to: Herb Sutter ([email protected]) Audience: SG7, EWG Contents 1 Overview .............................................................................................................................................................2 2 Language: Metaclasses .......................................................................................................................................7 3 Library: Example metaclasses .......................................................................................................................... 18 4 Applying metaclasses: Qt moc and C++/WinRT .............................................................................................. 35 5 Alternatives for sourcedefinition transform syntax .................................................................................... 41 6 Alternatives for applying the transform .......................................................................................................... 43 7 FAQs ................................................................................................................................................................. 46 8 Revision history ............................................................................................................................................... 51 Major changes in R3: Switched to function-style declaration syntax per SG7 direction in Albuquerque (old: $class M new: constexpr void M(meta::type target,
    [Show full text]
  • Generic Programming
    Generic Programming July 21, 1998 A Dagstuhl Seminar on the topic of Generic Programming was held April 27– May 1, 1998, with forty seven participants from ten countries. During the meeting there were thirty seven lectures, a panel session, and several problem sessions. The outcomes of the meeting include • A collection of abstracts of the lectures, made publicly available via this booklet and a web site at http://www-ca.informatik.uni-tuebingen.de/dagstuhl/gpdag.html. • Plans for a proceedings volume of papers submitted after the seminar that present (possibly extended) discussions of the topics covered in the lectures, problem sessions, and the panel session. • A list of generic programming projects and open problems, which will be maintained publicly on the World Wide Web at http://www-ca.informatik.uni-tuebingen.de/people/musser/gp/pop/index.html http://www.cs.rpi.edu/˜musser/gp/pop/index.html. 1 Contents 1 Motivation 3 2 Standards Panel 4 3 Lectures 4 3.1 Foundations and Methodology Comparisons ........ 4 Fundamentals of Generic Programming.................. 4 Jim Dehnert and Alex Stepanov Automatic Program Specialization by Partial Evaluation........ 4 Robert Gl¨uck Evaluating Generic Programming in Practice............... 6 Mehdi Jazayeri Polytypic Programming........................... 6 Johan Jeuring Recasting Algorithms As Objects: AnAlternativetoIterators . 7 Murali Sitaraman Using Genericity to Improve OO Designs................. 8 Karsten Weihe Inheritance, Genericity, and Class Hierarchies.............. 8 Wolf Zimmermann 3.2 Programming Methodology ................... 9 Hierarchical Iterators and Algorithms................... 9 Matt Austern Generic Programming in C++: Matrix Case Study........... 9 Krzysztof Czarnecki Generative Programming: Beyond Generic Programming........ 10 Ulrich Eisenecker Generic Programming Using Adaptive and Aspect-Oriented Programming .
    [Show full text]
  • Java Application Programming Interface (API) Java Application Programming Interface (API) Is a List of All Classes That Are Part of the Java Development Kit (JDK)
    Java Application Programming Interface (API) Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These prewritten classes provide a tremendous amount of functionality to a programmer. A programmer should be aware of these classes and should know how to use them. A complete listing of all classes in Java API can be found at Oracle’s website: http://docs.oracle.com/javase/7/docs/api/. Please visit the above site and bookmark it for future reference. Please consult this site often, especially when you are using a new class and would like to know more about its methods and fields. If you browse through the list of packages in the API, you will observe that there are packages written for GUI programming, networking programming, managing input and output, database programming, and many more. Please browse the complete list of packages and their descriptions to see how they can be used. In order to use a class from Java API, one needs to include an import statement at the start of the program. For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement: import java.util.Scanner; The above import statement allows the programmer to use any method listed in the Scanner class. Another choice for including the import statement is the wildcard option shown below: import java.util.*; This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer.
    [Show full text]
  • RICH: Automatically Protecting Against Integer-Based Vulnerabilities
    RICH: Automatically Protecting Against Integer-Based Vulnerabilities David Brumley, Tzi-cker Chiueh, Robert Johnson [email protected], [email protected], [email protected] Huijia Lin, Dawn Song [email protected], [email protected] Abstract against integer-based attacks. Integer bugs appear because programmers do not antici- We present the design and implementation of RICH pate the semantics of C operations. The C99 standard [16] (Run-time Integer CHecking), a tool for efficiently detecting defines about a dozen rules governinghow integer types can integer-based attacks against C programs at run time. C be cast or promoted. The standard allows several common integer bugs, a popular avenue of attack and frequent pro- cases, such as many types of down-casting, to be compiler- gramming error [1–15], occur when a variable value goes implementation specific. In addition, the written rules are out of the range of the machine word used to materialize it, not accompanied by an unambiguous set of formal rules, e.g. when assigning a large 32-bit int to a 16-bit short. making it difficult for a programmer to verify that he un- We show that safe and unsafe integer operations in C can derstands C99 correctly. Integer bugs are not exclusive to be captured by well-known sub-typing theory. The RICH C. Similar languages such as C++, and even type-safe lan- compiler extension compiles C programs to object code that guages such as Java and OCaml, do not raise exceptions on monitors its own execution to detect integer-based attacks.
    [Show full text]
  • A Metaobject Protocol for Fault-Tolerant CORBA Applications
    A Metaobject Protocol for Fault-Tolerant CORBA Applications Marc-Olivier Killijian*, Jean-Charles Fabre*, Juan-Carlos Ruiz-Garcia*, Shigeru Chiba** *LAAS-CNRS, 7 Avenue du Colonel Roche **Institute of Information Science and 31077 Toulouse cedex, France Electronics, University of Tsukuba, Tennodai, Tsukuba, Ibaraki 305-8573, Japan Abstract The corner stone of a fault-tolerant reflective The use of metalevel architectures for the architecture is the MOP. We thus propose a special implementation of fault-tolerant systems is today very purpose MOP to address the problems of general-purpose appealing. Nevertheless, all such fault-tolerant systems ones. We show that compile-time reflection is a good have used a general-purpose metaobject protocol (MOP) approach for developing a specialized runtime MOP. or are based on restricted reflective features of some The definition and the implementation of an object-oriented language. According to our past appropriate runtime metaobject protocol for implementing experience, we define in this paper a suitable metaobject fault tolerance into CORBA applications is the main protocol, called FT-MOP for building fault-tolerant contribution of the work reported in this paper. This systems. We explain how to realize a specialized runtime MOP, called FT-MOP (Fault Tolerance - MetaObject MOP using compile-time reflection. This MOP is CORBA Protocol), is sufficiently general to be used for other aims compliant: it enables the execution and the state evolution (mobility, adaptability, migration, security). FT-MOP of CORBA objects to be controlled and enables the fault provides a mean to attach dynamically fault tolerance tolerance metalevel to be developed as CORBA software. strategies to CORBA objects as CORBA metaobjects, enabling thus these strategies to be implemented as 1 .
    [Show full text]
  • Cpt S 122 – Data Structures Custom Templatized Data Structures In
    Cpt S 122 – Data Structures Custom Templatized Data Structures in C++ Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Classes Dynamic Memory Allocation and Data Structures Linked List insert, delete, isEmpty, printList Stacks push, pop Queues enqueue, dequeue Trees insertNode, inOrder, preOrder, postOrder Introduction Fixed-size data structures such as one-dimensional arrays and two- dimensional arrays. Dynamic data structures that grow and shrink during execution. Linked lists are collections of data items logically “lined up in a row” insertions and removals are made anywhere in a linked list. Stacks are important in compilers and operating systems: Insertions and removals are made only at one end of a stack—its top. Queues represent waiting lines; insertions are made at the back (also referred to as the tail) of a queue removals are made from the front (also referred to as the head) of a queue. Binary trees facilitate high-speed searching and sorting of data, efficient elimination of duplicate data items, representation of file-system directories compilation of expressions into machine language. Introduction (cont.) Classes, class templates, inheritance and composition is used to create and package these data structures for reusability and maintainability. Standard Template Library (STL) The STL is a major portion of the C++ Standard Library. The STL provides containers, iterators for traversing those containers algorithms for processing the containers’ elements. The STL packages data structures into templatized classes. The STL code is carefully written to be portable, efficient and extensible. Self-Referential Classes A self-referential class contains a pointer member that points to a class object of the same class type.
    [Show full text]
  • ETSI TS 102 222 V7.0.0 (2006-08) Technical Specification
    ETSI TS 102 222 V7.0.0 (2006-08) Technical Specification Integrated Circuit Cards (ICC); Administrative commands for telecommunications applications (Release 7) Release 7 2 ETSI TS 102 222 V7.0.0 (2006-08) Reference RTS/SCP-T00368 Keywords GSM, smart card, UMTS ETSI 650 Route des Lucioles F-06921 Sophia Antipolis Cedex - FRANCE Tel.: +33 4 92 94 42 00 Fax: +33 4 93 65 47 16 Siret N° 348 623 562 00017 - NAF 742 C Association à but non lucratif enregistrée à la Sous-Préfecture de Grasse (06) N° 7803/88 Important notice Individual copies of the present document can be downloaded from: http://www.etsi.org The present document may be made available in more than one electronic version or in print. In any case of existing or perceived difference in contents between such versions, the reference version is the Portable Document Format (PDF). In case of dispute, the reference shall be the printing on ETSI printers of the PDF version kept on a specific network drive within ETSI Secretariat. Users of the present document should be aware that the document may be subject to revision or change of status. Information on the current status of this and other ETSI documents is available at http://portal.etsi.org/tb/status/status.asp If you find errors in the present document, please send your comment to one of the following services: http://portal.etsi.org/chaircor/ETSI_support.asp Copyright Notification No part may be reproduced except as authorized by written permission. The copyright and the foregoing restriction extend to reproduction in all media.
    [Show full text]
  • Variable-Arity Generic Interfaces
    Variable-Arity Generic Interfaces T. Stephen Strickland, Richard Cobbe, and Matthias Felleisen College of Computer and Information Science Northeastern University Boston, MA 02115 [email protected] Abstract. Many programming languages provide variable-arity func- tions. Such functions consume a fixed number of required arguments plus an unspecified number of \rest arguments." The C++ standardiza- tion committee has recently lifted this flexibility from terms to types with the adoption of a proposal for variable-arity templates. In this paper we propose an extension of Java with variable-arity interfaces. We present some programming examples that can benefit from variable-arity generic interfaces in Java; a type-safe model of such a language; and a reduction to the core language. 1 Introduction In April of 2007 the C++ standardization committee adopted Gregor and J¨arvi's proposal [1] for variable-length type arguments in class templates, which pre- sented the idea and its implementation but did not include a formal model or soundness proof. As a result, the relevant constructs will appear in the upcom- ing C++09 draft. Demand for this feature is not limited to C++, however. David Hall submitted a request for variable-arity type parameters for classes to Sun in 2005 [2]. For an illustration of the idea, consider the remarks on first-class functions in Scala [3] from the language's homepage. There it says that \every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying." To achieve this integration of objects and closures, Scala's standard library pre-defines ten interfaces (traits) for function types, which we show here in Java-like syntax: interface Function0<Result> { Result apply(); } interface Function1<Arg1,Result> { Result apply(Arg1 a1); } interface Function2<Arg1,Arg2,Result> { Result apply(Arg1 a1, Arg2 a2); } ..
    [Show full text]
  • 13 Templates-Generics.Pdf
    CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 – 5 Gilad Bracha, Generics in the Java Programming Language Questions • If subtyping and inheritance are so great, why do we need type parameterization in object- oriented languages? • The great polymorphism debate – Subtype polymorphism • Apply f(Object x) to any y : C <: Object – Parametric polymorphism • Apply generic <T> f(T x) to any y : C Do these serve similar or different purposes? Outline • C++ Templates – Polymorphism vs Overloading – C++ Template specialization – Example: Standard Template Library (STL) – C++ Template metaprogramming • Java Generics – Subtyping versus generics – Static type checking for generics – Implementation of Java generics Polymorphism vs Overloading • Parametric polymorphism – Single algorithm may be given many types – Type variable may be replaced by any type – f :: tt => f :: IntInt, f :: BoolBool, ... • Overloading – A single symbol may refer to more than one algorithm – Each algorithm may have different type – Choice of algorithm determined by type context – Types of symbol may be arbitrarily different – + has types int*intint, real*realreal, ... Polymorphism: Haskell vs C++ • Haskell polymorphic function – Declarations (generally) require no type information – Type inference uses type variables – Type inference substitutes for variables as needed to instantiate polymorphic code • C++ function template – Programmer declares argument, result types of fctns – Programmers
    [Show full text]