SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
An overview of
Standard C++ TR1
        S G Ganesh
Agenda
    Introduction to TR1
    Utility Classes
    Containers
    Function Objects
    Type Traits
    Numerics
    Regular Expressions
    C-compatibility
    Compilers/Library Vendors Supporting TR1


09/06/08                                        2
Introduction To TR1
    TR1 - quot;Technical Report 1”
          New functionality added to C++ Standard Library
          Provided in std::tr1 namespace
          Not part of the C++ Standard (yet)
          Most of the vendors don’t support it (yet)
          Most of the TR1 components from Boost
          Only essential components are included
               Fills gaps left in the standard library
               not “less important”, “interesting” or “curious” components
    Expanded toolkit - many useful reusable components
    Helps you to be more productive
               Helps you avoid reinventing the wheel
09/06/08                                                                      3
Utilities – shared_ptr
    tr1::shared_ptr
          smart pointer for shared memory resource
          Automates resource(memory) deallocation
          Not a scoped pointer like std::auto_ptr
               Can be copied freely
               Can be used in containers
          Reference counted
               Overhead involved as need to maintain a counter
               Circular references are a trouble (they won’t be freed)
                 • Use tr1::weak_ptr for that
          tr1::shared_ptr complements std::auto_ptr
09/06/08                                                                  4
Shared_ptr - Example
#include <tr1/shared_ptr>
#include <vector>
#include <iostream>

using namespace std; using namespace std::tr1;

struct Object {
   Object(int val) { mem = val; cout << quot;Creating Objectquot; << mem; }
   ~Object() { cout << quot;Destroying Objectquot; << mem; }
   int mem;
};

int main() {
   typedef shared_ptr<Object> ObjectPtr;
   vector<ObjectPtr> SmartVector;
   SmartVector.push_back(ObjectPtr(new Object(1)));
   SmartVector.push_back(ObjectPtr(new Object(2)));
}
// prints: Creating Object1 Creating Object2
            Destroying Object1 Destroying Object2
 09/06/08                                                             5
Utilities – Tuple
    Generalization of the template std::pair
          std::pair is for two types, tr1::tuple is for N types
               N can be up to 10 or more
          make_tuple, that creates a tuple object
               similar to make_pair
          However syntax of tuple is different that of pair
               since first and second doesn’t scale
               so, use function template get<n> instead
    Useful for:
          Eliminating boilerplate container classes
          Particularly useful for multiple returning values from a
           function
          Storing more than one object in a container
09/06/08                                                              6
tuple - Example
#include <tr1/tuple>
#include <iostream>

using namespace std;
using namespace tr1; using namespace tr1::tuples;

tuple<char, int, float> tuple_creator() { return make_tuple ('b', 3, 3.0f); }

int main() {
   tuple<char, int, float> my_tuple ('1', 1, 1.0f);
   get<0>(my_tuple) = 'a';
   get<1>(my_tuple) = 2;
   get<2>(my_tuple) = 2.0f;

     cout << set_open('{') << set_delimiter('-') << set_close('}')
           << my_tuple << tuple_creator() << endl;
} 09/06/08
  // prints: {a-2-2} {b-3-3}                                                    7
Containers
    Hurray, at last, we have Hash maps!
          Standard associative containers are ordered
           (typically implemented as RB trees)
               Accessing an element is slower
          Unordered associative containers is a dire need
               Hashmaps promise constant time for element access
               tr1::unordered_set, tr1::unordered_multiset, tr1::
                unordered_map, tr1::unordered_multimap
          Might have better naming convention
               but “unordered” instead of “hash” abstracts
                implementation details
09/06/08                                                             8
Containers – Array
    Fixed Size Container
          Use when you know how many objects you need
    Satisfies requirements for a sequence
     container
               iterators, front(), back(), size() …
               So you can use them with standard algorithms
    Safe to pass/return them in functions easily and
     safely
          C style arrays error prone and strict no no!
               Use tr1::array instead if no need to interface with legacy
                code
09/06/08                                                                     9
Containers – Array - Example
#include <tr1/array>
#include <iostream>
using namespace std;

int main() {
   typedef tr1::array<double, 5> dbl_fixed_array;
   dbl_fixed_array my_array;

    dbl_fixed_array::iterator itr = my_array.begin();
    while(itr != my_array.end())
      *itr++ = 3.0;

    for(int i = 0; i < my_array.size(); i++)
        cout << my_array[i];
     // prints 3 3 3 3 3
}
09/06/08                                                10
Function Objects
    Four New Function Objects
        Named       Function Objects
              tr1::reference_wrapper and tr1::function
        Unnamed         Function Objects
              Produced by calls to tr1::mem_fn and tr1::bind




09/06/08                                                        11
Function Objects -
reference_wrapper
    Wrapper type that acts like a reference
     object
        But     unlike references, tr1::reference_wrapper
           objects can be copied and assigned to
               ref(x) creates an tr1::reference_wrapper<T> object
                 • where T is type of x
               Use cref(x) for creating tr1::reference_wrapper<const
                T>



09/06/08                                                            12
Function Objects – reference_wrapper -
 Example
#include <boost/ref.hpp>
#include <functional>
#include <iostream>

using namespace boost;
using namespace std;

struct functor {
   int operator()(int x, int y) { return x * y; };
};

template <class Func>
void apply(Func func, int arg1, int arg2) { cout << func(arg1, arg2); }

int main() {
  reference_wrapper<functor > rw1 = ref(functor());
  apply<functor>(rw1, 10, 20);
  reference_wrapper<multiplies<int> > rw3 = ref(multiplies<int>());
  apply<multiplies<int> >(rw3, 10, 20);
}
 09/06/08                                                                 13
Function Objects - function
    Wrapper type for a type that has function call operator
          e.g. function<int (int, float)>
               This refers to a type with function call operator which can take
                an int and a float and return an int
               Store any function-like ‘thing’: functions, member functions,
                functors
               First-class objects: Easily pass them to functions or copy
    Powerful because it can abstract object of any type
          that which has a function call operator of specific arguments
           and return types
    Store an action
          Call at any time; change at any time
    Implementation of the GoF Command pattern

09/06/08                                                                           14
Function Objects – function -
 Example
#include <tr1/function.hpp>
#include <iostream>

using namespace std;
using namespace std::tr1;

struct mul_functor {
   float operator()(int x, int y) const {
      return ((float) x) * y;
   };
};

void call(function<float (int, int)> &f, int x, int y) { cout << f(x, y); }

int main() {
   function<float (int, int)> func;
   func = mul_functor();
   call(func, 100, 200);
}
// prints: 20000
 09/06/08                                                                     15
Function Objects – mem_fn and bind

    Produced by calls to tr1::mem_fn and tr1::bind
    tr1::mem_fn
          generalized wrapper for pointer to functions
          first argument is the object on which call is done
               can be an object, a reference, a pointer, or a smart pointer!
          remaining are named arguments to the member function
    tr1::bind
          generalization of std::bind1st and std::bind2nd
    Why unnamed function objects?
          specifies template functions that return objects of these new
           types
          because we use these as function objects that we pass to
           template functions

09/06/08                                                                        16
Function Objects – mem_fn -
 Example
#include <tr1/function>
#include <tr1/shared_ptr>
#include <iostream>
#include <memory>

using namespace tr1; using namespace std;

struct some_struct { void print() { cout << quot;some_struct::print quot;; } };

template <class function>
void call(function fn) { // call through call wrapper
  fn(new some_struct());
   fn(shared_ptr<some_struct>(new some_struct()));
   fn(shared_ptr<some_struct>(new some_struct()).get());
}

int main() {
   call(mem_fn(&some_struct::print));
    // prints: some_struct::print some_struct::print some_struct::print
}
 09/06/08                                                                 17
Function Objects – bind - Example
#include <tr1/bind>
#include <iostream>

using namespace std; using namespace tr1;

template <class Binder>
void show(Binder binder) {
   int i = 5;
   int j = 10;
   binder(i, j);
}

void print(int t) { cout << t << 't'; }

int main() {
   show(bind(print, 0));
   show(bind(print, _1));
   show(bind(print, _2));
} // prints: 0 5 10
 09/06/08                                   18
Type Traits
    Useful for template programming
          instead of knowing nothing about the magic type “T” passed
           as type parameter in a template
          provides a set of “type predicates”
          can do “type transformations” when we have knowledge
           about what exactly is the type “T” in a template
    Template meta-programming
          Like it or not, template meta-programming is getting wide
           attention
          many of the things that can be done with type traits can also
           be done with function overloading
          but typetraits simplify things and makes meta-programming
           easier
09/06/08                                                                   19
Type Traits - Example
#include <tr1/type_traits>
#include <cstring>
#include <iostream>

using namespace std;
using namespace tr1;

struct do_copy {
    template<typename T>
    static void exec(T* dest, T* src, int num) {
       if(!is_pod<T>::value) {
         for(int i=0; i<num; ++i)
             *dest++ = *src++;
       }
       else
           memcpy(dest, src, sizeof(T)*num );
    }
};
 09/06/08                                          20
Type Traits – Example continued
struct S {
   S& operator = (const S &s) { cout << quot;copying Squot;<< endl; return s; }
};

int main() {
    do_copy c;
    S * sarr1 = new S[3];
    S sarr2[3];
    char str1[6] = quot;helloquot;;
    char str2[6] = quot;worldquot;;
    c.exec(str2, str1, sizeof(str1));
    cout << str2;
    c.exec(sarr2, sarr1, 3);
}
// prints: hello
     copying S
    copying S
     copying S
 09/06/08                                                                 21
Numerics
    Mathematical special functions
          twenty-three functions
               float, double, and long double overloads
    Engineering and scientific computing becomes easier
          No reinventing the wheel/no writing of textbook code
          For established and widely used functionality (in specific
           domains) e.g: cylindrical Bessel functions, confluent
           hypergeometric functions
    Four random number generators and nine types of
     binomial distributions
               You can combine those generators and distributions

09/06/08                                                                22
Regular Expressions
    Finally we have pattern matching capabilities
          Powerful search and replace features
               use tr1::regex to store a regular expression
               pass the tr1::regex object to tr1::regex_match, tr1::
                regex_search, or tr1::regex_replace
        Templated thingy, so not limited to searching
         standard strings
        Perl can no more boast that it’s the best

        Use iterators to step through the
         subsequences/matches for the regular expression

09/06/08                                                                23
Regular Expressions - Example
#include <tr1/regex>
#include <iostream>
using namespace std;
using namespace tr1;

int main() {
   //regex_merge example
   const string one(quot;tr1 quot;);
   const regex two(quot;stuff is quot;);
   const string three(“coolquot;);
   cout << regex_merge(one, two, three); // prints: tr1 stuff is cool

      // regex_match example
      const string good_str (“4323-4342quot;);
      const string bad_str (“645433-323quot;);
      const regex match_expr(quot;(d{4}-d{4})quot;);

      cout<< boolalpha << regex_match(good_str, match_expr)
            << regex_match(bad_str, match_expr) << endl; // prints: true false
}
    09/06/08                                                                     24
C Compatibility
    TR1 adopts the changes in C standard
          C++ standard is based on 1990 C standard
          C standard amended in 1995; revised in 1999 (C99)
    Adopted features from C standard
          Low-level control of floating point operations
          Several new functions from C standard library
          fixed width integral types
          new format specifiers for printf/scanf family
    New argument matching rules for math functions as in
     C standard
          Currently ambiguous: for call to atan2(flt, dbl), atan2(float,
           float), atan2(double, double), and atan2(long double, long
           double) equally good matches
           Under new rules atan2(double, double) is the best match
09/06/08                                                                    25
Compilers/Vendors Supporting TR1

    Dinkumware (www.dinkumware.com)
          first commerical library vendor to provide TR1 (as part of the
           Dinkum C++ Library)
    Boost (www.boost.org)
          Many of the components of TR1 from Boost library
          A separate download package of TR1 components already
           available
    Project GNU (www.gnu.org)
          Parts of TR1 in their C++ Standard Library
          Can be used with g++
    HP aCC
          RogueWave doesn’t provide TR1 yet
          Testing of Boost TR1/aCC planned
               with sample programs, the components seem to work fine
09/06/08                                                                    26
Wrapping Up
    Links
        The    standard committee document on TR1

           http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1
          The Boost TR1
           http://freespace.virgin.net/boost.regex/tr1/index.html
 Q&A
 Thank You!


09/06/08                                                       27

Más contenido relacionado

La actualidad más candente

[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeAkira Takahashi
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingFrancesco Casalegno
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Lab Log Summer 2016 - Sheng Li
Lab Log Summer 2016 - Sheng LiLab Log Summer 2016 - Sheng Li
Lab Log Summer 2016 - Sheng LiSheng Li
 
Python 如何執行
Python 如何執行Python 如何執行
Python 如何執行kao kuo-tung
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyRoberto Polli
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocolShiyao Ma
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?Dina Goldshtein
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 

La actualidad más candente (20)

[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend Range
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Lab Log Summer 2016 - Sheng Li
Lab Log Summer 2016 - Sheng LiLab Log Summer 2016 - Sheng Li
Lab Log Summer 2016 - Sheng Li
 
Python 如何執行
Python 如何執行Python 如何執行
Python 如何執行
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are Easy
 
Gcrc talk
Gcrc talkGcrc talk
Gcrc talk
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 
Link list
Link listLink list
Link list
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 

Destacado

Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreModern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreGanesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
OCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsOCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsGanesh Samarthyam
 
IBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryIBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryMarkTaylorIBM
 
IBM Websphere MQ Basic
IBM Websphere MQ BasicIBM Websphere MQ Basic
IBM Websphere MQ BasicPRASAD BHATKAR
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerSematext Group, Inc.
 
Docker for Java Developers
Docker for Java DevelopersDocker for Java Developers
Docker for Java DevelopersNGINX, Inc.
 
Docker introduction
Docker introductionDocker introduction
Docker introductiondotCloud
 
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesRootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesDaniel Garcia (a.k.a cr0hn)
 

Destacado (15)

Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - BangaloreModern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
Modern Software Architecure Bootcamp - 2nd July 2016 - Bangalore
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
OCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsOCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certifications
 
IBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster RecoveryIBM MQ - High Availability and Disaster Recovery
IBM MQ - High Availability and Disaster Recovery
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
IBM Websphere MQ Basic
IBM Websphere MQ BasicIBM Websphere MQ Basic
IBM Websphere MQ Basic
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
 
Docker for Java Developers
Docker for Java DevelopersDocker for Java Developers
Docker for Java Developers
 
Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker imagesRootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
RootedCON 2017 - Docker might not be your friend. Trojanizing Docker images
 

Similar a An Overview Of Standard C++Tr1

Unit 4
Unit 4Unit 4
Unit 4siddr
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG ManiaplAnkur Shrivastava
 
PLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptxPLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptxRichard Martens
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
TAUS USER CONFERENCE 2009, Normalization of translation memories
TAUS USER CONFERENCE 2009, Normalization of translation memoriesTAUS USER CONFERENCE 2009, Normalization of translation memories
TAUS USER CONFERENCE 2009, Normalization of translation memoriesTAUS - The Language Data Network
 
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdfDatabase & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdfInSync2011
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17Daniel Eriksson
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.Mohamed Fawzy
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphiMax Kleiner
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta ProgrammingReggie Meisler
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design PatternsDerek Brown
 

Similar a An Overview Of Standard C++Tr1 (20)

Unit 4
Unit 4Unit 4
Unit 4
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG Maniapl
 
PLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptxPLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptx
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
TAUS USER CONFERENCE 2009, Normalization of translation memories
TAUS USER CONFERENCE 2009, Normalization of translation memoriesTAUS USER CONFERENCE 2009, Normalization of translation memories
TAUS USER CONFERENCE 2009, Normalization of translation memories
 
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdfDatabase & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphi
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Threads
ThreadsThreads
Threads
 
08 -functions
08  -functions08  -functions
08 -functions
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 

Más de Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 

Más de Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 

Último

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Último (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

An Overview Of Standard C++Tr1

  • 1. An overview of Standard C++ TR1 S G Ganesh
  • 2. Agenda  Introduction to TR1  Utility Classes  Containers  Function Objects  Type Traits  Numerics  Regular Expressions  C-compatibility  Compilers/Library Vendors Supporting TR1 09/06/08 2
  • 3. Introduction To TR1  TR1 - quot;Technical Report 1”  New functionality added to C++ Standard Library  Provided in std::tr1 namespace  Not part of the C++ Standard (yet)  Most of the vendors don’t support it (yet)  Most of the TR1 components from Boost  Only essential components are included  Fills gaps left in the standard library  not “less important”, “interesting” or “curious” components  Expanded toolkit - many useful reusable components  Helps you to be more productive  Helps you avoid reinventing the wheel 09/06/08 3
  • 4. Utilities – shared_ptr  tr1::shared_ptr  smart pointer for shared memory resource  Automates resource(memory) deallocation  Not a scoped pointer like std::auto_ptr  Can be copied freely  Can be used in containers  Reference counted  Overhead involved as need to maintain a counter  Circular references are a trouble (they won’t be freed) • Use tr1::weak_ptr for that  tr1::shared_ptr complements std::auto_ptr 09/06/08 4
  • 5. Shared_ptr - Example #include <tr1/shared_ptr> #include <vector> #include <iostream> using namespace std; using namespace std::tr1; struct Object { Object(int val) { mem = val; cout << quot;Creating Objectquot; << mem; } ~Object() { cout << quot;Destroying Objectquot; << mem; } int mem; }; int main() { typedef shared_ptr<Object> ObjectPtr; vector<ObjectPtr> SmartVector; SmartVector.push_back(ObjectPtr(new Object(1))); SmartVector.push_back(ObjectPtr(new Object(2))); } // prints: Creating Object1 Creating Object2 Destroying Object1 Destroying Object2 09/06/08 5
  • 6. Utilities – Tuple  Generalization of the template std::pair  std::pair is for two types, tr1::tuple is for N types  N can be up to 10 or more  make_tuple, that creates a tuple object  similar to make_pair  However syntax of tuple is different that of pair  since first and second doesn’t scale  so, use function template get<n> instead  Useful for:  Eliminating boilerplate container classes  Particularly useful for multiple returning values from a function  Storing more than one object in a container 09/06/08 6
  • 7. tuple - Example #include <tr1/tuple> #include <iostream> using namespace std; using namespace tr1; using namespace tr1::tuples; tuple<char, int, float> tuple_creator() { return make_tuple ('b', 3, 3.0f); } int main() { tuple<char, int, float> my_tuple ('1', 1, 1.0f); get<0>(my_tuple) = 'a'; get<1>(my_tuple) = 2; get<2>(my_tuple) = 2.0f; cout << set_open('{') << set_delimiter('-') << set_close('}') << my_tuple << tuple_creator() << endl; } 09/06/08 // prints: {a-2-2} {b-3-3} 7
  • 8. Containers  Hurray, at last, we have Hash maps!  Standard associative containers are ordered (typically implemented as RB trees)  Accessing an element is slower  Unordered associative containers is a dire need  Hashmaps promise constant time for element access  tr1::unordered_set, tr1::unordered_multiset, tr1:: unordered_map, tr1::unordered_multimap  Might have better naming convention  but “unordered” instead of “hash” abstracts implementation details 09/06/08 8
  • 9. Containers – Array  Fixed Size Container  Use when you know how many objects you need  Satisfies requirements for a sequence container  iterators, front(), back(), size() …  So you can use them with standard algorithms  Safe to pass/return them in functions easily and safely  C style arrays error prone and strict no no!  Use tr1::array instead if no need to interface with legacy code 09/06/08 9
  • 10. Containers – Array - Example #include <tr1/array> #include <iostream> using namespace std; int main() { typedef tr1::array<double, 5> dbl_fixed_array; dbl_fixed_array my_array; dbl_fixed_array::iterator itr = my_array.begin(); while(itr != my_array.end()) *itr++ = 3.0; for(int i = 0; i < my_array.size(); i++) cout << my_array[i]; // prints 3 3 3 3 3 } 09/06/08 10
  • 11. Function Objects  Four New Function Objects  Named Function Objects  tr1::reference_wrapper and tr1::function  Unnamed Function Objects  Produced by calls to tr1::mem_fn and tr1::bind 09/06/08 11
  • 12. Function Objects - reference_wrapper  Wrapper type that acts like a reference object  But unlike references, tr1::reference_wrapper objects can be copied and assigned to  ref(x) creates an tr1::reference_wrapper<T> object • where T is type of x  Use cref(x) for creating tr1::reference_wrapper<const T> 09/06/08 12
  • 13. Function Objects – reference_wrapper - Example #include <boost/ref.hpp> #include <functional> #include <iostream> using namespace boost; using namespace std; struct functor { int operator()(int x, int y) { return x * y; }; }; template <class Func> void apply(Func func, int arg1, int arg2) { cout << func(arg1, arg2); } int main() { reference_wrapper<functor > rw1 = ref(functor()); apply<functor>(rw1, 10, 20); reference_wrapper<multiplies<int> > rw3 = ref(multiplies<int>()); apply<multiplies<int> >(rw3, 10, 20); } 09/06/08 13
  • 14. Function Objects - function  Wrapper type for a type that has function call operator  e.g. function<int (int, float)>  This refers to a type with function call operator which can take an int and a float and return an int  Store any function-like ‘thing’: functions, member functions, functors  First-class objects: Easily pass them to functions or copy  Powerful because it can abstract object of any type  that which has a function call operator of specific arguments and return types  Store an action  Call at any time; change at any time  Implementation of the GoF Command pattern 09/06/08 14
  • 15. Function Objects – function - Example #include <tr1/function.hpp> #include <iostream> using namespace std; using namespace std::tr1; struct mul_functor { float operator()(int x, int y) const { return ((float) x) * y; }; }; void call(function<float (int, int)> &f, int x, int y) { cout << f(x, y); } int main() { function<float (int, int)> func; func = mul_functor(); call(func, 100, 200); } // prints: 20000 09/06/08 15
  • 16. Function Objects – mem_fn and bind  Produced by calls to tr1::mem_fn and tr1::bind  tr1::mem_fn  generalized wrapper for pointer to functions  first argument is the object on which call is done  can be an object, a reference, a pointer, or a smart pointer!  remaining are named arguments to the member function  tr1::bind  generalization of std::bind1st and std::bind2nd  Why unnamed function objects?  specifies template functions that return objects of these new types  because we use these as function objects that we pass to template functions 09/06/08 16
  • 17. Function Objects – mem_fn - Example #include <tr1/function> #include <tr1/shared_ptr> #include <iostream> #include <memory> using namespace tr1; using namespace std; struct some_struct { void print() { cout << quot;some_struct::print quot;; } }; template <class function> void call(function fn) { // call through call wrapper fn(new some_struct()); fn(shared_ptr<some_struct>(new some_struct())); fn(shared_ptr<some_struct>(new some_struct()).get()); } int main() { call(mem_fn(&some_struct::print)); // prints: some_struct::print some_struct::print some_struct::print } 09/06/08 17
  • 18. Function Objects – bind - Example #include <tr1/bind> #include <iostream> using namespace std; using namespace tr1; template <class Binder> void show(Binder binder) { int i = 5; int j = 10; binder(i, j); } void print(int t) { cout << t << 't'; } int main() { show(bind(print, 0)); show(bind(print, _1)); show(bind(print, _2)); } // prints: 0 5 10 09/06/08 18
  • 19. Type Traits  Useful for template programming  instead of knowing nothing about the magic type “T” passed as type parameter in a template  provides a set of “type predicates”  can do “type transformations” when we have knowledge about what exactly is the type “T” in a template  Template meta-programming  Like it or not, template meta-programming is getting wide attention  many of the things that can be done with type traits can also be done with function overloading  but typetraits simplify things and makes meta-programming easier 09/06/08 19
  • 20. Type Traits - Example #include <tr1/type_traits> #include <cstring> #include <iostream> using namespace std; using namespace tr1; struct do_copy { template<typename T> static void exec(T* dest, T* src, int num) { if(!is_pod<T>::value) { for(int i=0; i<num; ++i) *dest++ = *src++; } else memcpy(dest, src, sizeof(T)*num ); } }; 09/06/08 20
  • 21. Type Traits – Example continued struct S { S& operator = (const S &s) { cout << quot;copying Squot;<< endl; return s; } }; int main() { do_copy c; S * sarr1 = new S[3]; S sarr2[3]; char str1[6] = quot;helloquot;; char str2[6] = quot;worldquot;; c.exec(str2, str1, sizeof(str1)); cout << str2; c.exec(sarr2, sarr1, 3); } // prints: hello copying S copying S copying S 09/06/08 21
  • 22. Numerics  Mathematical special functions  twenty-three functions  float, double, and long double overloads  Engineering and scientific computing becomes easier  No reinventing the wheel/no writing of textbook code  For established and widely used functionality (in specific domains) e.g: cylindrical Bessel functions, confluent hypergeometric functions  Four random number generators and nine types of binomial distributions  You can combine those generators and distributions 09/06/08 22
  • 23. Regular Expressions  Finally we have pattern matching capabilities  Powerful search and replace features  use tr1::regex to store a regular expression  pass the tr1::regex object to tr1::regex_match, tr1:: regex_search, or tr1::regex_replace  Templated thingy, so not limited to searching standard strings  Perl can no more boast that it’s the best  Use iterators to step through the subsequences/matches for the regular expression 09/06/08 23
  • 24. Regular Expressions - Example #include <tr1/regex> #include <iostream> using namespace std; using namespace tr1; int main() { //regex_merge example const string one(quot;tr1 quot;); const regex two(quot;stuff is quot;); const string three(“coolquot;); cout << regex_merge(one, two, three); // prints: tr1 stuff is cool // regex_match example const string good_str (“4323-4342quot;); const string bad_str (“645433-323quot;); const regex match_expr(quot;(d{4}-d{4})quot;); cout<< boolalpha << regex_match(good_str, match_expr) << regex_match(bad_str, match_expr) << endl; // prints: true false } 09/06/08 24
  • 25. C Compatibility  TR1 adopts the changes in C standard  C++ standard is based on 1990 C standard  C standard amended in 1995; revised in 1999 (C99)  Adopted features from C standard  Low-level control of floating point operations  Several new functions from C standard library  fixed width integral types  new format specifiers for printf/scanf family  New argument matching rules for math functions as in C standard  Currently ambiguous: for call to atan2(flt, dbl), atan2(float, float), atan2(double, double), and atan2(long double, long double) equally good matches  Under new rules atan2(double, double) is the best match 09/06/08 25
  • 26. Compilers/Vendors Supporting TR1  Dinkumware (www.dinkumware.com)  first commerical library vendor to provide TR1 (as part of the Dinkum C++ Library)  Boost (www.boost.org)  Many of the components of TR1 from Boost library  A separate download package of TR1 components already available  Project GNU (www.gnu.org)  Parts of TR1 in their C++ Standard Library  Can be used with g++  HP aCC  RogueWave doesn’t provide TR1 yet  Testing of Boost TR1/aCC planned  with sample programs, the components seem to work fine 09/06/08 26
  • 27. Wrapping Up  Links  The standard committee document on TR1 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1  The Boost TR1 http://freespace.virgin.net/boost.regex/tr1/index.html  Q&A  Thank You! 09/06/08 27