SlideShare une entreprise Scribd logo
1  sur  51
Yaser Zhian
Fanafzar Game Studio
IGDI, Workshop 01, August 2nd, 2012
If you write C-style code, you’ll end
up with C-style bugs.
                                -- Bjarne Stroustrup



If you write Java-style code, you’ll
have Java-level performance.


          http://yaserzt.com/                          1
   C++98: First Standard
   C++03: minor changes, mostly the standard
   TR1
   C++11
     Larger and more complex
     Leaner and meaner at the same time




               http://yaserzt.com/              2
   C++ has no replacement if you want
     total control
     best performance/$
     to take advantage of hardware (multicore, GPU, …)
     to program the way you want
     zero-overhead abstractions




                http://yaserzt.com/                       3
   Mixed-paradigm, statically-typed, compiled,
    widespread, many libraries, YDPFWYDU,
    works everywhere and with everything.
   No ABI, tooling very complex.
   Libraries don’t work together, complex and
    vast, bad teachers, intimidating for beginners,
    seems too verbose and low-level.


              http://yaserzt.com/                     4
   “Don’t break people’s code”
   Oriented towards library-developers
   Lower-cost abstractions
   Easier for beginners (a little)
   “If it can go into the Standard Library, do not
    put it in the language”



               http://yaserzt.com/                    5
http://yaserzt.com/   6
   What is the type of a + b?
     Even if you don’t know, the compiler always does.
     decltype(a + b) c;
     Instead of double c;
   auto instructs the compiler to infer type from
    initializing expression, e.g.
     auto foo = a * b + c * d;
     auto bar =
             new std::map<std::string, bool>;
               http://yaserzt.com/                        7
   Not always a convenience feature.
     What’s the return type of
      template <typename T, typename U>
      ??? Add (T const & a, U const & b)
      {
           return a + b;
      }
     One answer is decltype(T() + U())
      ▪ (not entirely correct)
     The correct answer is decltype(a + b)
     But that won’t compile.

                    http://yaserzt.com/       8
   That’s the motivation behind the new
    function declaration syntax:
     auto Fun (type1 p1, type2 p2, ...)
     -> returntype;
   The previous function then becomes:
     template <typename T, typename U>
     auto Add (T const & a, U const & b)
     -> decltype(a + b);
              http://yaserzt.com/          9
   Think of them as unnamed functions, written in the middle of
    your code, plus much more.
   [] (int a, int b) -> int {return a + b;}
   Lambdas are far-reaching and far more complicated under
    the hood, with many more features.
   auto g =
        [] (int a, int b) -> int {return a + b;};
    int c = g(43, -1);
   std::function<int (int, int)> h =
        [] (int a, int b) -> int {return a + b;};
    int d = h(41, 1);

                 http://yaserzt.com/                               10
   std::for_each (v.begin(), v.end(),
       [](float f) {std::cout << f << std::endl;}
    );

   int x = 7;
    std::for_each (v.begin(), v.end(),
       [x](float & f) {f += x;}
    );

   float sum = 0.0f;
    std::for_each (v.begin(), v.end(),
       [&sum](float f) {sum += f;}
    );

               http://yaserzt.com/                  11
class StupidCollection
{
        std::vector<int> m_data;
public:
        void apply (std::function<int (int)> f)
        {
            for (auto i = m_data.begin(), e = m_data.end(); i != e; ++i)
                *i = f (*i);
        }

       template <typename Func>
       void apply (Func f)
       {
           for (auto i = m_data.begin(), e = m_data.end(); i != e; ++i)
               *i = f (*i);
       }
};


                  http://yaserzt.com/                                      12
   C++ used to have a tendency to copy stuff around if
    you weren’t paying attention!
   What happens when we call this function?
     vector<string> GenerateNames ()
      {
          return
               vector<string>(50, string(100, '*'));
      }
     A whole lot of useless stuff are created and copied around.
   All sorts of techniques and tricks to avoid those copies.
   Hold that thought for a minute.
                 http://yaserzt.com/                                13
   string s = string("Hello") + " " + "world.";
    1.   string (char const * that)
    2.   operator + (char const * that)
    3.   operator + (char const * that)
    4.   this ultimately called the copy c’tor string (string const &
         that).
    5.   (Unrelated note) Allocations can be avoided with “Expression
         Templates”.
   C++11 introduces “rvalue references” to let you work with (kinda)
    temporary objects.
     Rvalue references are denoted with &&.
     e.g. int && p = 3;


                   http://yaserzt.com/                                  14
   In situations where you used to copy the data
    from an object into another object, if your first
    object is an rvalue (i.e. temporary) now you can
    “move” the data from that to this.
   Two important usages of rvalue references are
    “move construction” and “move assignment”.
     e.g. string (string && that);// move c'tor
     and string & operator = (string && that);
     // move assignment
               http://yaserzt.com/                      15
template <typename T>
class Matrix
{
private:
      T * m_data;
      unsigned m_rows, m_columns;
public:
      Matrix (unsigned rows, unsigned columns);
      ~Matrix ();
      Matrix (Matrix<T> const & that);
      template <typename U> Matrix (Matrix<U> const & that);
      Matrix<T> & operator = (Matrix<T> const & that);
      Matrix (Matrix<T> && that);
      Matrix<T> & operator = (Matrix<T> && that);
      ...
};

                http://yaserzt.com/                            16
template <typename T>
class Matrix
{
       ...
       unsigned rows () const;
       unsigned columns () const;
       unsigned size () const;
       T & operator () (unsigned row, unsigned col);    // m(5, 7) = 0;
       T const & operator () (unsigned row, unsigned col) const;

       template <typename U>
       auto operator + (Matrix<U> const & rhs) const
               -> Matrix<decltype(T() + U())>;

       template <typename U>
       auto operator * (Matrix<U> const & rhs) const
               -> Matrix<decltype(T() * U() + T() * U())>;
};

                  http://yaserzt.com/                                     17
Matrix (unsigned rows, unsigned columns)
    : m_rows (rows), m_columns (columns)
    , m_data (new T [rows * columns])
{
}

~Matrix ()
{
    delete[] m_data;
}

Matrix (Matrix<T> const & that)
    : m_rows (that.m_rows), m_columns (that.m_columns)
    , m_data (new T [that.m_rows * that.m_columns])
{
    std::copy (
        that.m_data, that.m_data + (m_rows * m_columns), m_data
    );
}
                  http://yaserzt.com/                             18
Matrix<T> & operator = (Matrix<T> const & that)
{
    if (this != &that)
    {
        m_rows = that.m_rows;
        m_columns = that.m_columns;
        T * new_data = new T [m_rows * m_columns];
        std::copy (
            that.m_data, that.m_data + (m_rows * m_columns), new_data
        );
        delete[] m_data;
        m_data = new_data;
    }
    return *this;
}




                  http://yaserzt.com/                                   19
Matrix (Matrix<T> && that)
    : m_rows (that.m_rows), m_columns (that.m_columns)
    , m_data (that.m_data)
{
    that.m_rows = that.m_columns = 0;
    that.m_data = nullptr;
}




                http://yaserzt.com/                      20
Matrix<T> & operator = (Matrix<T> && that)
{
    if (this != &that)
    {
        T * old_data = m_data;
        m_rows = that.m_rows;
        m_columns = that.m_columns;
        m_data = that.data;
        that.m_rows = rhs.m_columns = 0;
        that.m_data = nullptr;
        delete[] old_data;
    }
    return *this;
}



                http://yaserzt.com/          21
struct SomeClass
{
    string s;
    vector<int> v;

     // WRONG! WRONG! WRONG!
     // Doesn’t move, just copies.
     SomeClass (SomeClass && that)
         : s (that.s), v (that.v)
     {}

     SomeClass (SomeClass && that)
         : s (std::move(that.s)), v (std::move(that.v))
     {}
};


                 http://yaserzt.com/                      22
 In principle, std::move should look like this:
  template <typename T>
  ??? move (??? something)
  {
        return something;
  }
 What should the argument type be?
     T&& ?
     T& ?
     Both? Neither?
   We need to be able to pass in both lvalues and rvalues.

                 http://yaserzt.com/                          23
   We can overload move() like this:
     move (T && something)
     move (T & something)
     But that will lead to exponential explosion of overloads if the
      function has more arguments.
   “Reference collapse” rule in C++98:
     int& & is collapsed to int&.
   In C++11, the rules are: (in addition to the above)
     int&& & is collapsed to int&.
     int& && is collapsed to int&.
     int&& && is collapsed to int&&.

                   http://yaserzt.com/                                  24
   Therefore, only the T&& version should be enough.
     If you pass in an lvalue to our move, the actual argument
      type will collapse into T&, which is what we want
      (probably.)
   So, move looks like this thus far:
    template <typename T>
    ??? move (T && something)
    {
         return something;
    }
                 http://yaserzt.com/                              25
   Now, what is the return type?
     T&& ?
     It should be T&& in the end.
     But if we declare it so, and move() is called on an
      lvalue,
      ▪   then T will be SomeType&
      ▪   then T&& will be SomeType& &&
      ▪   then it will collapse into SomeType&
      ▪   then we will be returning an lvalue reference from move(),
          which will prevent any moving at all.
     We need a way to remove the & if T already has one.

                    http://yaserzt.com/                                26
   We need a mechanism to map one type to another
     In this case, to map T& and T&& to T, and T to T.
   There is no simple way to describe the process, but
    this is how it’s done:
     template<typename T> struct RemoveReference
      {
           typedef T type;
      };
     With that, RemoveReference<int>::type will be
      equivalent to int.
     But we are not done.
                  http://yaserzt.com/                     27
 Now we specialize:
  template<typename T>
  struct RemoveReference<T&>
  {
       typedef T type;
  };
 template<typename T>
  struct RemoveReference<T &&>
  {
       typedef T type;
  };
 Now, RemoveReference<int &>::type will be int too.


              http://yaserzt.com/                      28
 Our move now has the correct signature:
  template <typename T>
  typename RemoveReference<T>::type &&
  move (T && something)
  {
        return something;
  }
 But it’s not correct. That “something” in there is
  an lvalue, remember?

             http://yaserzt.com/                       29
 …so we cast it to an rvalue reference:
  template <typename T>
  typename RemoveReference<T>::type &&
       move (T && something)
  {
       return static_cast<
             typename RemoveReference<T>::type &&
       >
             (something);
  }
 Hopefully, this is correct now!




              http://yaserzt.com/                   30
   Templates with variable number of arguments
   For example
    template <typename... Ts>
    size_t log (int severity, char const * msg,
                    Ts&&... vs);
   Remember the old way?
     size_t log (int severity, char const * msg, ...);
     Using va_list, va_start, va_arg and va_end in <cstdarg>
   Or
     #define LOG_ERROR(msg, ...) 
                 log (SevError, msg, __VA_ARGS__)
                 http://yaserzt.com/                            31
   Almost the same for classes:
    template <typename... Ts>
    class ManyParents
         : Ts...
    {
         ManyParents ()
              : Ts ()...
         {}
    };
   Now these are valid:
    ManyParents<A> a;
    ManyParents<A, B> b;
              http://yaserzt.com/   32
 template <typename T, typename... PTs>
  T * Create (T * parent, PTs&&... ps)
  {
         T* ret = new T;
         ret->create (parent, ps...);
         return ret;
  }
 PTs and ps are not types, values, arrays, tuples or
  initializer lists.
 They are new “things”.

              http://yaserzt.com/                       33
 Rules of expansion are very interesting:
   Ts...               → T1,T2,…,Tn
   Ts&&...             → T1&&,…,Tn&&
   A<Ts,U>...          → A<T1,U>,…,A<Tn,U>
   A<Ts,Us>...         → A<T1,U1>,…,A<Tn,Un>
   f(42, vs...)        → f(42,v1,…,vn)
   f(42, vs)...        → f(42,v1),…,f(42,vn)
 One more operation you can do:
  size_t items = sizeof...(Ts); // or vs
           http://yaserzt.com/                  34
   Let’s implement the sizeof... operator as an example.
    template <typename... Ts> struct CountOf;

    template <> struct CountOf<>
    {
        enum { value = 0 };
    };

    template <typename T, typename... Ts>
    struct CountOf
    {
        enum { value = CountOf<Ts...>::value + 1 };
    };
   Use CountOf like this:
    size_t items = CountOf<Ts>::value;
                   http://yaserzt.com/                      35
#include <future>
string flip (string s) {
    reverse (s.begin(), s.end());
    return s;
}
int main () {
    vector<future<string>> v;
    v.push_back (async ([] {return flip(   " ,olleH");}));
    v.push_back (async ([] {return flip(" weN evarB");}));
    v.push_back (async ([] {return flip(    "!dlroW");}));
    for (auto& i : v)
        cout << i.get();
    cout << endl;
    return 0;
}
                http://yaserzt.com/                          36
   Initializer lists (std::initializer_list<T>)
   static_assert (expr, "message");
   Delegating constructors
   Member initialization in class declaration
   Explicitly overriding inherited methods
   Explicitly using or not using default methods



              http://yaserzt.com/                   37
   Functions, constructors and class members as
    constexprs.
   UTF8, UTF16, UTF32 and raw string literals
   User-defined literals
   Libraries for regular expressions, shared
    pointers, threads , tuples, atomic operations,
    working with the file system,… (mostly from
    TR1 and Boost.)

              http://yaserzt.com/                    38
   Wikipedia article on C++11 at
    http://en.wikipedia.org/wiki/C%2B%2B11
   Scott Meyers, Herb Sutter and Andrei Alexandrescu –
    C++ and Beyond (lectures and presentations)
   Presentations by Bjarne Stroustrup and Stephan T.
    Lavavej from Going Native 2012
   Microsoft’s implementation of the C++11 Standard
    Library (accompanying VC11 Beta)
   C++11 published standard: ISO/IEC 14882:2011
     A draft (similar to the published standard) is available at
      http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf



                   http://yaserzt.com/                                    39
If you have a shotgun, you don’t have to use it to kill mosquitoes.
                                                                But it’s a lot of fun!




Contact us at http://fanafzar.com/
And me at y@yaserzt.com
   Hardware is the platform – everything else is
    just cruft
   Abstractions are necessary (d’oh!)
   Good abstractions let you express more
   Good abstractions let you declare intent
   Good abstractions can increase performance
     memcpy() vs. std::copy()
     qsort()vs. std::sort()


              http://yaserzt.com/                   41
class thread
{
public:
    class id;

     thread ();

     template <class F, class... Args>
     explicit thread (F&& f, Args&&... args);

     ~thread();
     bool joinable() const;
     void join();
     void detach();

     id get_id() const;

     static unsigned int hardware_concurrency();
};

                    http://yaserzt.com/            42
namespace this_thread
{
    thread::id get_id();
    void yield ();
    void sleep_until (abs_time);
    void sleep_for (rel_time);
}




            http://yaserzt.com/    43
   enable_if
   Type traits
   Sample std::copy




             http://yaserzt.com/   44
http://yaserzt.com/   45
http://yaserzt.com/   46
http://yaserzt.com/   47
http://yaserzt.com/   48
http://yaserzt.com/   49
http://yaserzt.com/   50

Contenu connexe

Tendances

2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays kinan keshkeh
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Olve Maudal
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsPhilip Schwarz
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1Philip Schwarz
 
Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)Open Labs Albania
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义yiditushe
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13Chris Ohk
 

Tendances (20)

2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
C++11
C++11C++11
C++11
 
Templates
TemplatesTemplates
Templates
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)
 
C++ 11
C++ 11C++ 11
C++ 11
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs Chromium
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 

Similaire à C++11 - A Change in Style - v2.0

Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview QuestionsGradeup
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 

Similaire à C++11 - A Change in Style - v2.0 (20)

Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates2
Templates2Templates2
Templates2
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
C++ references
C++ referencesC++ references
C++ references
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Namespaces
NamespacesNamespaces
Namespaces
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Introduction to c part 2
Introduction to c   part  2Introduction to c   part  2
Introduction to c part 2
 

Dernier

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Dernier (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

C++11 - A Change in Style - v2.0

  • 1. Yaser Zhian Fanafzar Game Studio IGDI, Workshop 01, August 2nd, 2012
  • 2. If you write C-style code, you’ll end up with C-style bugs. -- Bjarne Stroustrup If you write Java-style code, you’ll have Java-level performance. http://yaserzt.com/ 1
  • 3. C++98: First Standard  C++03: minor changes, mostly the standard  TR1  C++11  Larger and more complex  Leaner and meaner at the same time http://yaserzt.com/ 2
  • 4. C++ has no replacement if you want  total control  best performance/$  to take advantage of hardware (multicore, GPU, …)  to program the way you want  zero-overhead abstractions http://yaserzt.com/ 3
  • 5. Mixed-paradigm, statically-typed, compiled, widespread, many libraries, YDPFWYDU, works everywhere and with everything.  No ABI, tooling very complex.  Libraries don’t work together, complex and vast, bad teachers, intimidating for beginners, seems too verbose and low-level. http://yaserzt.com/ 4
  • 6. “Don’t break people’s code”  Oriented towards library-developers  Lower-cost abstractions  Easier for beginners (a little)  “If it can go into the Standard Library, do not put it in the language” http://yaserzt.com/ 5
  • 8. What is the type of a + b?  Even if you don’t know, the compiler always does.  decltype(a + b) c;  Instead of double c;  auto instructs the compiler to infer type from initializing expression, e.g.  auto foo = a * b + c * d;  auto bar = new std::map<std::string, bool>; http://yaserzt.com/ 7
  • 9. Not always a convenience feature.  What’s the return type of template <typename T, typename U> ??? Add (T const & a, U const & b) { return a + b; }  One answer is decltype(T() + U()) ▪ (not entirely correct)  The correct answer is decltype(a + b)  But that won’t compile. http://yaserzt.com/ 8
  • 10. That’s the motivation behind the new function declaration syntax:  auto Fun (type1 p1, type2 p2, ...) -> returntype;  The previous function then becomes:  template <typename T, typename U> auto Add (T const & a, U const & b) -> decltype(a + b); http://yaserzt.com/ 9
  • 11. Think of them as unnamed functions, written in the middle of your code, plus much more.  [] (int a, int b) -> int {return a + b;}  Lambdas are far-reaching and far more complicated under the hood, with many more features.  auto g = [] (int a, int b) -> int {return a + b;}; int c = g(43, -1);  std::function<int (int, int)> h = [] (int a, int b) -> int {return a + b;}; int d = h(41, 1); http://yaserzt.com/ 10
  • 12. std::for_each (v.begin(), v.end(), [](float f) {std::cout << f << std::endl;} );  int x = 7; std::for_each (v.begin(), v.end(), [x](float & f) {f += x;} );  float sum = 0.0f; std::for_each (v.begin(), v.end(), [&sum](float f) {sum += f;} ); http://yaserzt.com/ 11
  • 13. class StupidCollection { std::vector<int> m_data; public: void apply (std::function<int (int)> f) { for (auto i = m_data.begin(), e = m_data.end(); i != e; ++i) *i = f (*i); } template <typename Func> void apply (Func f) { for (auto i = m_data.begin(), e = m_data.end(); i != e; ++i) *i = f (*i); } }; http://yaserzt.com/ 12
  • 14. C++ used to have a tendency to copy stuff around if you weren’t paying attention!  What happens when we call this function?  vector<string> GenerateNames () { return vector<string>(50, string(100, '*')); }  A whole lot of useless stuff are created and copied around.  All sorts of techniques and tricks to avoid those copies.  Hold that thought for a minute. http://yaserzt.com/ 13
  • 15. string s = string("Hello") + " " + "world."; 1. string (char const * that) 2. operator + (char const * that) 3. operator + (char const * that) 4. this ultimately called the copy c’tor string (string const & that). 5. (Unrelated note) Allocations can be avoided with “Expression Templates”.  C++11 introduces “rvalue references” to let you work with (kinda) temporary objects.  Rvalue references are denoted with &&.  e.g. int && p = 3; http://yaserzt.com/ 14
  • 16. In situations where you used to copy the data from an object into another object, if your first object is an rvalue (i.e. temporary) now you can “move” the data from that to this.  Two important usages of rvalue references are “move construction” and “move assignment”.  e.g. string (string && that);// move c'tor  and string & operator = (string && that); // move assignment http://yaserzt.com/ 15
  • 17. template <typename T> class Matrix { private: T * m_data; unsigned m_rows, m_columns; public: Matrix (unsigned rows, unsigned columns); ~Matrix (); Matrix (Matrix<T> const & that); template <typename U> Matrix (Matrix<U> const & that); Matrix<T> & operator = (Matrix<T> const & that); Matrix (Matrix<T> && that); Matrix<T> & operator = (Matrix<T> && that); ... }; http://yaserzt.com/ 16
  • 18. template <typename T> class Matrix { ... unsigned rows () const; unsigned columns () const; unsigned size () const; T & operator () (unsigned row, unsigned col); // m(5, 7) = 0; T const & operator () (unsigned row, unsigned col) const; template <typename U> auto operator + (Matrix<U> const & rhs) const -> Matrix<decltype(T() + U())>; template <typename U> auto operator * (Matrix<U> const & rhs) const -> Matrix<decltype(T() * U() + T() * U())>; }; http://yaserzt.com/ 17
  • 19. Matrix (unsigned rows, unsigned columns) : m_rows (rows), m_columns (columns) , m_data (new T [rows * columns]) { } ~Matrix () { delete[] m_data; } Matrix (Matrix<T> const & that) : m_rows (that.m_rows), m_columns (that.m_columns) , m_data (new T [that.m_rows * that.m_columns]) { std::copy ( that.m_data, that.m_data + (m_rows * m_columns), m_data ); } http://yaserzt.com/ 18
  • 20. Matrix<T> & operator = (Matrix<T> const & that) { if (this != &that) { m_rows = that.m_rows; m_columns = that.m_columns; T * new_data = new T [m_rows * m_columns]; std::copy ( that.m_data, that.m_data + (m_rows * m_columns), new_data ); delete[] m_data; m_data = new_data; } return *this; } http://yaserzt.com/ 19
  • 21. Matrix (Matrix<T> && that) : m_rows (that.m_rows), m_columns (that.m_columns) , m_data (that.m_data) { that.m_rows = that.m_columns = 0; that.m_data = nullptr; } http://yaserzt.com/ 20
  • 22. Matrix<T> & operator = (Matrix<T> && that) { if (this != &that) { T * old_data = m_data; m_rows = that.m_rows; m_columns = that.m_columns; m_data = that.data; that.m_rows = rhs.m_columns = 0; that.m_data = nullptr; delete[] old_data; } return *this; } http://yaserzt.com/ 21
  • 23. struct SomeClass { string s; vector<int> v; // WRONG! WRONG! WRONG! // Doesn’t move, just copies. SomeClass (SomeClass && that) : s (that.s), v (that.v) {} SomeClass (SomeClass && that) : s (std::move(that.s)), v (std::move(that.v)) {} }; http://yaserzt.com/ 22
  • 24.  In principle, std::move should look like this: template <typename T> ??? move (??? something) { return something; }  What should the argument type be?  T&& ?  T& ?  Both? Neither?  We need to be able to pass in both lvalues and rvalues. http://yaserzt.com/ 23
  • 25. We can overload move() like this:  move (T && something)  move (T & something)  But that will lead to exponential explosion of overloads if the function has more arguments.  “Reference collapse” rule in C++98:  int& & is collapsed to int&.  In C++11, the rules are: (in addition to the above)  int&& & is collapsed to int&.  int& && is collapsed to int&.  int&& && is collapsed to int&&. http://yaserzt.com/ 24
  • 26. Therefore, only the T&& version should be enough.  If you pass in an lvalue to our move, the actual argument type will collapse into T&, which is what we want (probably.)  So, move looks like this thus far: template <typename T> ??? move (T && something) { return something; } http://yaserzt.com/ 25
  • 27. Now, what is the return type?  T&& ?  It should be T&& in the end.  But if we declare it so, and move() is called on an lvalue, ▪ then T will be SomeType& ▪ then T&& will be SomeType& && ▪ then it will collapse into SomeType& ▪ then we will be returning an lvalue reference from move(), which will prevent any moving at all.  We need a way to remove the & if T already has one. http://yaserzt.com/ 26
  • 28. We need a mechanism to map one type to another  In this case, to map T& and T&& to T, and T to T.  There is no simple way to describe the process, but this is how it’s done:  template<typename T> struct RemoveReference { typedef T type; };  With that, RemoveReference<int>::type will be equivalent to int.  But we are not done. http://yaserzt.com/ 27
  • 29.  Now we specialize: template<typename T> struct RemoveReference<T&> { typedef T type; };  template<typename T> struct RemoveReference<T &&> { typedef T type; };  Now, RemoveReference<int &>::type will be int too. http://yaserzt.com/ 28
  • 30.  Our move now has the correct signature: template <typename T> typename RemoveReference<T>::type && move (T && something) { return something; }  But it’s not correct. That “something” in there is an lvalue, remember? http://yaserzt.com/ 29
  • 31.  …so we cast it to an rvalue reference: template <typename T> typename RemoveReference<T>::type && move (T && something) { return static_cast< typename RemoveReference<T>::type && > (something); }  Hopefully, this is correct now! http://yaserzt.com/ 30
  • 32. Templates with variable number of arguments  For example template <typename... Ts> size_t log (int severity, char const * msg, Ts&&... vs);  Remember the old way?  size_t log (int severity, char const * msg, ...);  Using va_list, va_start, va_arg and va_end in <cstdarg>  Or  #define LOG_ERROR(msg, ...) log (SevError, msg, __VA_ARGS__) http://yaserzt.com/ 31
  • 33. Almost the same for classes: template <typename... Ts> class ManyParents : Ts... { ManyParents () : Ts ()... {} };  Now these are valid: ManyParents<A> a; ManyParents<A, B> b; http://yaserzt.com/ 32
  • 34.  template <typename T, typename... PTs> T * Create (T * parent, PTs&&... ps) { T* ret = new T; ret->create (parent, ps...); return ret; }  PTs and ps are not types, values, arrays, tuples or initializer lists.  They are new “things”. http://yaserzt.com/ 33
  • 35.  Rules of expansion are very interesting:  Ts... → T1,T2,…,Tn  Ts&&... → T1&&,…,Tn&&  A<Ts,U>... → A<T1,U>,…,A<Tn,U>  A<Ts,Us>... → A<T1,U1>,…,A<Tn,Un>  f(42, vs...) → f(42,v1,…,vn)  f(42, vs)... → f(42,v1),…,f(42,vn)  One more operation you can do: size_t items = sizeof...(Ts); // or vs http://yaserzt.com/ 34
  • 36. Let’s implement the sizeof... operator as an example. template <typename... Ts> struct CountOf; template <> struct CountOf<> { enum { value = 0 }; }; template <typename T, typename... Ts> struct CountOf { enum { value = CountOf<Ts...>::value + 1 }; };  Use CountOf like this: size_t items = CountOf<Ts>::value; http://yaserzt.com/ 35
  • 37. #include <future> string flip (string s) { reverse (s.begin(), s.end()); return s; } int main () { vector<future<string>> v; v.push_back (async ([] {return flip( " ,olleH");})); v.push_back (async ([] {return flip(" weN evarB");})); v.push_back (async ([] {return flip( "!dlroW");})); for (auto& i : v) cout << i.get(); cout << endl; return 0; } http://yaserzt.com/ 36
  • 38. Initializer lists (std::initializer_list<T>)  static_assert (expr, "message");  Delegating constructors  Member initialization in class declaration  Explicitly overriding inherited methods  Explicitly using or not using default methods http://yaserzt.com/ 37
  • 39. Functions, constructors and class members as constexprs.  UTF8, UTF16, UTF32 and raw string literals  User-defined literals  Libraries for regular expressions, shared pointers, threads , tuples, atomic operations, working with the file system,… (mostly from TR1 and Boost.) http://yaserzt.com/ 38
  • 40. Wikipedia article on C++11 at http://en.wikipedia.org/wiki/C%2B%2B11  Scott Meyers, Herb Sutter and Andrei Alexandrescu – C++ and Beyond (lectures and presentations)  Presentations by Bjarne Stroustrup and Stephan T. Lavavej from Going Native 2012  Microsoft’s implementation of the C++11 Standard Library (accompanying VC11 Beta)  C++11 published standard: ISO/IEC 14882:2011  A draft (similar to the published standard) is available at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf http://yaserzt.com/ 39
  • 41. If you have a shotgun, you don’t have to use it to kill mosquitoes. But it’s a lot of fun! Contact us at http://fanafzar.com/ And me at y@yaserzt.com
  • 42. Hardware is the platform – everything else is just cruft  Abstractions are necessary (d’oh!)  Good abstractions let you express more  Good abstractions let you declare intent  Good abstractions can increase performance  memcpy() vs. std::copy()  qsort()vs. std::sort() http://yaserzt.com/ 41
  • 43. class thread { public: class id; thread (); template <class F, class... Args> explicit thread (F&& f, Args&&... args); ~thread(); bool joinable() const; void join(); void detach(); id get_id() const; static unsigned int hardware_concurrency(); }; http://yaserzt.com/ 42
  • 44. namespace this_thread { thread::id get_id(); void yield (); void sleep_until (abs_time); void sleep_for (rel_time); } http://yaserzt.com/ 43
  • 45. enable_if  Type traits  Sample std::copy http://yaserzt.com/ 44