Optional?. Agenda Type traits intro Interface & usage Caveats.

Slides:



Advertisements
Similar presentations
1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
Advertisements

Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.
Linked Lists CENG 213 Data Structures.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
C++ Programming Languages
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
1 Objects and ClassesStefan Kluth 1.6Objects and Classes 1.6What is an Object? 1.7Objects and Classes 1.8Object Interface, Class Inheritance, Polymorphism.
hashing1 Hashing It’s not just for breakfast anymore!
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
Templates. Class templates – why? Writing programs we often use abstract data types such as stack, queue or tree. Implementations of these types may be.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Lecture 11 vector and Free Store Bjarne Stroustrup
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Java Implementation: Part 3 Software Construction Lecture 8.
C Tokens Identifiers Keywords Constants Operators Special symbols.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
C#.Net Development Version 1.0. Overview Nullable Datatype Description ? HasValue Lifted Conversions null coalescing operator ?? Partial Classes Copyright.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
GPCE'04, Vancouver 1 Towards a General Template Introspection Library in C++ István Zólyomi, Zoltán Porkoláb Department of Programming Languages and Compilers.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
3. Controlling Program Flow Methods, parameters, and return values Boolean expressions Conditional branching Loops.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
A Generic List Class and Linked Lists Andy Wang Data Structures, Algorithms, and Generic Programming.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
P4Helpers P4Helpers.h provides static helper functions for kinematic calculation on objects deriving from I4Momentum. Anthony Denton-Farnworth, The University.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
C++ 程序语言设计 Chapter 12: Dynamic Object Creation. Outline  Object creation process  Overloading new & delete.
Chapter 6 LISTS AND STRINGS 1. List Definition 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Doubly Linked 3. Linked.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
The List ADT Reading: Sections 3.2, 3.3, 3.5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
C++ Lesson 1.
STRICT_VARIANT A simpler variant in C++ Chris Beck
Data types Data types Basic types
Type Traits By Reggie Meisler.
Computing with C# and the .NET Framework
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Array Lists Chapter 6 Section 6.1 to 6.3
understanding memory usage by a c++ program
null, true, and false are also reserved.
CS212: Object Oriented Analysis and Design
Initialization List.
Built-In (a.k.a. Native) Types in C++
2. Second Step for Learning C++ Programming • Data Type • Char • Float
15 – Sequential Containers
Presentation transcript:

Optional?

Agenda Type traits intro Interface & usage Caveats

Why? Uninitialized variables cause lots of bugs Removes much need for 2-stage initialization of objects A cheap 0 or 1 element container Internal storage. Much preferable over scoped_ptr + heap allocation Much less bloat & faster compilation than boost::optional

Type traits are meta functions! is_integer ::value => true is_floating_point ::value => false alignment_of ::value => 128 remove_reference ::type => T is_same ::value => false is_convertible ::value => true Very useful when writing generic code

Implemented with template specialization // Default template struct is_floating_point { enum { value = false; } }; template<> struct is_floating_point { enum { value = true; } }; template<> struct is_floating_point { enum { value = true; } };

Useful for static dispatch, among other things.. template T my_cool_algorithm(T t) { return my_cool_algorithm_impl ::value>(t); } template T my_cool_algorithm_impl(T t); template T my_cool_algorithm_impl(T t) { // int optimized version } template T my_cool_algorithm_impl(T t) { // float optimized version }

Optional interface struct Nothing {}; template class Optional { Optional(); Optional(Nothing); // Note implicit Optional(const T& value); // Note implicit Optional(const Optional & copy); Optional & operator=(Nothing); Optional & operator=(const T& value); Optional & operator=(const Optional & rhs); bool isSet() const; isSet() T& get(); const T& get() const; }; // Override placement new to allow constructing elements without copying template inline void* operator new(size_t, fb::Optional & optional); // Convenience function template const T& getValueOr(const Optional & optional, const T& defaultValue) const; template T& getValueOr(Optional & optional, T& defaultValue) const;

Basic usage Optional i; ASSERT(!i.isSet()); i = 23; ASSERT(i.isSet() && i.get()==23); i = Nothing(); ASSERT(!i.isSet());

Return from functions // C style bool sqrt(double n, double& result); Optional sqrt(double n); Client code won’t forget to check the bool All-or-nothing guarantee, can’t break output variables

Member variables not always valid class X { Optional m_resultCache; }; Clearer than using -1 or other "invalid values“

Single item container class X { Optional m_activeWeapon; }; Does not require DefaultConstructible objects No heap allocations! Uses placement new internally Useful to store RAII objects

Expressive interface class X { void setLookForEnemyAroundPosition( const Optional & position); const Optional & getLookForEnemyAroundPosition(); };

Simplifying code class Target { // Remove, use optional instead! bool isValid() const; }; void foo(Optional t); void bar(Target t); void baz(Target t); Often little code that need complexity of invalid objects Helps maintenance – expressive client code

Caveats in current implementation Aligned types double in size No implicit bool conversion Unnecessary branch for some types Most of them can be fixed simply

Aligned types double in size sizeof(Optional ) == 2 * sizeof(Vec3) For Vec3, the pad data can be used

No implicit bool conversion Missing safe implicit type conversion to bool if (Optional xRoot = sqrt(x))

Unnecessary branch for some types ~Optional() { if (!HasTrivialDestructor ::Value && m_initialized) m_storage.destruct(); } Will get C++0x features in all of our compilers soon Until then types can be registered as having a trivial, no- op destructor

Further reading Unit tests in OptionalTest.cpp Static tests in HasTrivialDestructor.cpp, AlignedStorage.cpp and Optional.cpp Design rationale for boost.optional html Nullable i C#