Making New Pseudo-Languages with C++

Similar documents
An introduction to C++ template programming

Tutorial 7. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 7

Tutorial 6. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 6

C++11 and Compiler Update

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

use static size for this buffer

Part X. Advanced C ++

ECE 3574: Dynamic Polymorphism using Inheritance

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

An Insight Into Inheritance, Object Oriented Programming, Run-Time Type Information, and Exceptions PV264 Advanced Programming in C++

Intermediate C++ 1/83

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Object Oriented Paradigm

G52CPP C++ Programming Lecture 20

C++ Programming Lecture 7 Software Engineering Group

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Data Abstraction. Hwansoo Han

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Chapter 1 Getting Started

Friendship in Service of Testing

Advanced Systems Programming

PyROOT: Seamless Melting of C++ and Python. Pere MATO, Danilo PIPARO on behalf of the ROOT Team

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CS93SI Handout 04 Spring 2006 Apr Review Answers

Modern C++ Design. Generic Programming and Design Patterns Applied. Andrei Alexandrescu. AAddison-Wesley

Index. Symbols. bit sequence, 27 ^ (exclusive OR) operator, 30 hexadecimal number, 27 left shift (<<) operator, 31 right shift (>>) operator, 32

September 10,

C++ Programming Lecture 7 Software Engineering Group

Fast Introduction to Object Oriented Programming and C++

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

New Programming Paradigms

Botet C++ generic match function P0050

And Even More and More C++ Fundamentals of Computer Science

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

C++ Coding Standards. 101 Rules, Guidelines, and Best Practices. Herb Sutter Andrei Alexandrescu. Boston. 'Y.'YAddison-Wesley

Software Design Tidbits. Bálint Joó, Scientific Computing Group Jefferson Lab

Chapter 15 - C++ As A "Better C"

CE221 Programming in C++ Part 1 Introduction

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

AN OVERVIEW OF C++ 1

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Introduce C# as Object Oriented programming language. Explain, tokens,

COEN244: Class & function templates

Interview Questions of C++

Database Systems on Modern CPU Architectures

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced

Introduction to C++ Systems Programming

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

C++ (Non for C Programmer) (BT307) 40 Hours

CSE 333 Lecture 9 - intro to C++

Review&Preview 1/23/15, 4:08:07 PM 1. 3rd edition - standardized, and standard library allows programmer to start from a higher level

CSE 303: Concepts and Tools for Software Development

Remedial C Now that we can actually use it Pete Williamson

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

CS3157: Advanced Programming. Outline

Modern C++ Design. Generic Programming and Design Patterns Applied. Andrei Alexandrescu

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS 376b Computer Vision

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

A brief introduction to C programming for Java programmers

Improve your C++! John Richardson. Lab Study Meeting 2013

Concepts of Object-Oriented Programming. Richard Berger Johannes Kepler University Linz

Explicit Conversion Operator Draft Working Paper

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus

2 ADT Programming User-defined abstract data types

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

C++ for System Developers with Design Pattern

Modern C++ Design. Generic Programming and Design Patterns Applied. Andrei Alexandrescu. .~Addison-Wesley

Advanced C++ Topics. Alexander Warg, 2017

Multimedia-Programmierung Übung 3

04-24/26 Discussion Notes

Distance Learning Advanced C++ - Programming Models, boost and Parallel Computing

A few important patterns and their connections

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade

C++11 Introduction to the New Standard. Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science

GEA 2017, Week 4. February 21, 2017

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

MODERN AND LUCID C++ ADVANCED

AspectC++ A Language Overview

6 Architecture of C++ programs

Introduction to C++11 and its use inside Qt

CCReflect has a few interesting features that are quite desirable for DigiPen game projects:

Distributing Communication with Real-Time Message Queues

CS11 Intro C++ Spring 2018 Lecture 1

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

An Introduction to Template Metaprogramming

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

PIC 10A Objects/Classes

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Part III. Advanced C ++

RAII and Smart Pointers. Ali Malik

Structured bindings with polymorphic lambas

Assignment operator string class c++ Assignment operator string class c++.zip

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Transcription:

Making New Pseudo-Languages with C++ Build You a C++ For Great Good ++ A 10,000 Metre Talk by David Williams-King

Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++ 4/4 Metaprogramming & Frontends

Introduction About me CBoard member for nearly 10 years http://cboard.cprogramming.com/ C++ game engine developer Most large-scale C++ projects have their own idioms, and invent their own dialect of C++ Thinking about this explicitly is useful

C++ Language Specifications Pre-standard: iostream.h, ad-hoc libraries C++98: first standard TR1 (C++03): regular exp, smart pointers, hash tables, etc (just library changes) Boost: major C++ library which influenced TR1 C++11 (C++0x): second major standard, syntax changes (template >>), auto type inference, etc C++14 (upcoming): auto return types, better lambdas, etc.

C++ ecosystems Major C++ compilers Borland C++ Builder Microsoft Visual Studio C++ (MSVC) GNU Compiler Collection (g++) LLVM (clang) IBM's xlc++, Intel's icc, EDG front-end (Coverity...) Boost: high-quality C++ libraries Atomics, message-passing, serialization, regexes, preprocessors (Wave), co-routines, random number generators, shared pointers, embedded Python,...

Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++ 4/4 Metaprogramming & Frontends

Partially-Specified Behaviour Polymorphism through template types // from GCC 4.9's bits/stl_set.h namespace std { template<typename _Key, typename _Compare = std::less<_key>, typename _Alloc = std::allocator<_key> > class set { //... Polymorphism through inheritance, interface specification, composition, etc Polymorphism through virtual functions!

Virtual Functions Overriding a method with a new version crops up in C code, in the runtime linker, etc. Some languages do this everywhere (Smalltalk, Java, etc.) C++ lets you opt in with virtual Normal function calls are bound statically; virtual function calls are bound dynamically

Multimethods Call a function polymorphically based on the types of multiple different classes e.g. collisions in a game a.k.a. multiple dispatch (double dispatch) Report on language support for Multi-Methods and Open-Methods for C++ -- Stroustrup Can emulate with visitor design pattern polymorphic source method creates a visitor class which has accept(foo), accept(bar), etc Target class hierarchy has polymorphic visit(visitor)

Visitor Design Pattern struct Visitor { virtual ~Visitor() {} virtual void visit(const Foo1 &f) = 0; virtual void visit(const Foo2 &f) = 0; }; struct Foo { virtual void accept(visitor &v) { v.visit(*this); } virtual void collide(const Foo &other); }; class Foo1 : public Foo {}; class Foo2 : public Foo {}; void Foo1::collide(const Foo &other) { struct NewFooFunction : public Visitor { /*... */ } f; other.accept(f); // one level of polymorphism because collide is virtual; // another level because of the visitor's overloading }

Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++ 4/4 Metaprogramming & Frontends

Operator overloading Simple operator overloading Point operator + (const Point &other) const { return Point(x + other.x, y + other.y); } External operator overloading std::ostream &operator << (std::ostream &o, const Foo &f) { o << f.getname(); return o; } Type-conversion overloading operator std::string () const { return StreamAsString() << x << ',' << y; }

StreamAsString Use << operator anywhere a string is expected void print(const std::string &s); print(streamasstring() << Answer: << 42); How? std::ostringstream template operator << operator std::string()

#include <sstream> #include <string> StreamAsString class StreamAsString { private: std::ostringstream stream; public: template <typename T> StreamAsString &operator << (const T &data) { stream << data; return *this; } }; operator std::string() const { return stream.str(); }

Memory Management C-style arrays, unchecked accesses, unsafe New Standard Template Library containers like std::vector, std::map, std::unordered_map, etc. they can do bounds-checking and auto-resizing Automatic memory management with smart pointers and reference counting (C++03/Boost) Program-wide memory management with allocator pools

Smart Pointers How to write a smart pointer implementation: catch dereferences (operator *, operator ->) catch copying (operator =, copy constructor) provide comparisons, conversions (operator bool) std::shared_ptr, std::weak_ptr shared_ptr does ref counting weak_ptr can be converted to shared but doesn't count towards the reference count

Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++ 4/4 Metaprogramming & Frontends

Metaprogramming C++ is Turing-complete (obviously) So is the preprocessor: http://stackoverflow.com/questions/3136686/is-the-c99-preprocessor-turing-complete So are templates (see Modern C++ Design by Andrei Alexandrescu -- the library is called Loki) Basic ideas like singleton, factories, pools But also typelists, traits, multimethods, functors

Object Messages/Event Systems A class wants to announce a state change without knowing who is interested common in GUI toolkits and game engines Ways of implementing this: observer design pattern (quite klunky) event class with functors (Boost.Signals, templates) global event managing system (my favourite) separate pre-processing pass (e.g. Qt moc)

Serialization/Marshalling Turn an object into a string and back again (for sending over a network, storing on disk, etc) Boost.Serialization example: class C { private: friend class boost::serialization::access; template <typename Archive> void serialize(archive &ar, const unsigned ver) { ar & x; // like << and >> combined together ar & y; } private: int x, y; };

Reflection Want the ability to query the functions of an unknown class, call a function by name, instantiate a class by name at runtime powerful when combined with serialization One example: Qt's Meta-Object Compiler (moc) extra pre-processing pass that constructs a metaobject for relevant classes also generates plumbing for object messages

Synthesis add events to objects (Boost.Signals, etc) store events in templated thread-safe queues automatically serialize and deserialize events (Boost.Serialization) send events over the network asynchronously (Boost.Asio) manage memory with shared pointers define events in XML or Lua...

ācta The End.

References (1/3) More about C++ in general CBoard http://cboard.cprogramming.com/ C++11 http://www.learncpp.com/cpp-tutorial/b-1-introduction-to-c11/ Boost! Learn it!! http://boost.org/ Misc: function pointers http://www.newty.de/fpt/ Slide references Images from Learn You a Haskell for Great Good http://learnyouahaskell.com/

References (2/3) Metaprogramming and language extensions Book: Modern C++ Design by Andrei Alexandrescu (will turn you into a template wizard!) Or get the code online http://loki-lib.sourceforge.net/index.php?n=main.moderncdesign Qt Meta-Object system http://qt-project.org/doc/qt-4.8/metaobjects.html Boost http://boost.org/ Especially Boost.Signals, for event systems: http://www.boost.org/doc/libs/1_56_0/doc/html/signals/tutorial.html#idp426643280 My rant about Qt signals/slots (Boost is much better!) http://elfery.net/blog/signals.html

References (3/3) Serialization Google's protocol buffers https://github.com/google/protobuf/ Multimethods Report on language support for Multi-Methods and Open-Methods for C++ http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2216.pdf For stuff that actually exists, see Multiple Dispatch on Wikipedia http://en.wikipedia.org/wiki/multiple_dispatch Design patterns Visitor, Observer, Composition; Event Notifier: http://www.marco.panizza.name/dispensetm/slides/exerc/eventnotifier/eventnotifier.html

(backup slides)

Undefined Functions Convention: prototype a method but don't define the function body (to create an abstract class) C++ canonized this with pure virtual functions class C { public: virtual void foo() = 0; } Effective way to define abstract classes

C++11 Virtual Function Features New virtual function controls override: this function must override a base-class function (like Java 5's @Override annotation) final: can't be overridden (like Java's final) default: use default code for default constructor, copy-constructor, assignment operator, or destructor delete: prevent function from being called virtual void foo() override; virtual void foo() final; virtual void foo() = default; virtual void foo() = delete;

Function Pointers http://www.newty.de/fpt/ Original C function pointers are straightforward: void print(const char *s) { puts(s); } void (*func)(const char *) = &print; func( Hello ); (*func)( Hello );

Function Pointers Pointers to member functions must specify scope class C { public: int add(int i) const { return i+i; } int mul(int i) const { return i*i; } }; int (C::*func)(int) = &C::add; C c, *p = &c; int result1 = (c.*func)(5); int result2 = (p->*func)(5); int result3 = (*this.*func)(5);