SlideShare uma empresa Scribd logo
1 de 29
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel
                                      www.sela.co.il
Variadic Templates
Concepts
Other Wild Ideas
• Visual Studio 2010: Some features are supported
• Visual Studio 2012: Some more features are supported




                                                                          Not supported yet
                                       Visual Studio 2012
     Visual Studio 2010




                          Automatic                         Concurrency                       Variadic
                          variables,                        library                           templates
                          decltype                          Memory                            Custom
                          Rvalue                            model                             literals
                          references                                                          Delegating
                          Lambda                                                              constructors
                          functions
• Comparison chart between many other compilers:
  http://s.sashag.net/rpST0u
The problem with existing templates is that the
  number of parameters is constant, consider:
      tuple, printf, other type-safe va_list, …

template <typename T1> struct tuple {
  T1 first;
};
template <typename T1, typename T2> struct tuple {
  T1 first; T2 second;
};
template <typename T1, typename T2, typename T3> struct tuple {
  T1 first; T2 second; T3 third;
};
//VC11 <tuple> does this with macros, going up to 10 parameters
New syntax for unbounded type parameter lists and
  function parameter lists
      “Dot-dot-dot is where the fun begins”

template <typename... Ts>
void foo(Ts&&... vs); //note: Ts is NOT a type, vs is NOT a variable

foo(42);                        foo(5, "Hello, World", vector<int>());

template <typename... Ts>
struct tuple; //requires some serious work!

tuple<int, float, string> tup(42, 42.0f, "42");
get<1>(tup) += 3.0f;             cout << get<2>(tup) << endl;
New syntax for type list expansion
      …and there’s also a new operator: sizeof...()


template <typename... Ts>
int passthrough_printf(const char* fmt, Ts&&... vs)
  return printf(fmt, vs...);
}
template <typename... Ts>
class mixin : public Ts... {}; //will inherit from all Ts specified

//note: the following two statements ARE NOT THE SAME!
foo(goo(vs...));    ≡ foo(goo(v1, v2, v3));
foo(goo(vs)...);    ≡ foo(goo(v1), goo(v2), goo(v3));
Typically, you have a base case that does something (or
  nothing) and “recurse” to it from the variadic case
      Not true recursion (different template)

template <typename... Ts>
void print(Ts&&... vs) {} //base case, will match empty list, do nothing

template <typename T, typename... Ts>
void print(T&& v, Ts&&... vs) {
  cout << v << endl;
  print(vs...); //”recursive” case; note that any decent compiler
}               //will inline the whole thing into the caller
Alternatively, the base case can be a bounded number
  of parameters to which we “recurse”


template <typename T1, typename T2>
bool assertContained(T1&& v1, T2&& v2) {
  return v1 == v2;
}

template <typename T1, typename T2, typename... Ts>
bool assertContained(T1&& v1, T2&& v2, Ts&&... vs) {
  return (v1 == v2 || assertContained(v1, vs...));
}
Using the compiler’s template mechanism to do work
  at compile-time
     Theorem: C++ templates are Turing-complete

//recursive case:
template <int N> struct fibo {
  static const int value = fibo<N-1>::value + fibo<N-2>::value;
};
//base cases:
template <> struct fibo<0> { static const int value = 1; };
template <> struct fibo<1> { static const int value = 1; };

cout << fibo<14>::value; //compile-time!
template <typename T> void print(const T& t) {}
template <typename T> void print(const T& t,
  typename enable_if<
    is_pointer<T>::value, void*
  >::type dummy = nullptr) {         From <type_traits>
  printf("%p", t);                   (simple specializations)
}
template <typename T> void print(const T& t,
  typename enable_if<
    is_convertible<T,string>::value, void*     template <
                                                bool, typename T = void
  >::type dummy = nullptr) {
                                               >
  printf("%s", string(t).c_str());             struct enable_if {};
}
                                                template <typename T>
                                                struct enable_if<true,T> {
                                                  typedef T type;
                                                };
We now develop a partial tuple<...>
     (Practically) No limit on number of type parameters
     Following A. Alexandrescu’s GoingNative 2012 talk

template <typename... Ts> struct tuple {};
template <typename T, typename... Ts>
struct tuple : private tuple<Ts...> {
  T _head;
public:
  tuple(T&& v, Ts&&... vs) :
    _head(v), tuple<Ts...>(vs...) {}
  //many more methods omitted
};
• Note that tuple<T1,T2> derives from tuple<T2>
     tuple<>           tuple<>          tuple<>
     (empty)           (empty)          (empty)
                      tuple<T1>        tuple<T2>
                       T1 _head        T2 _head
 tuple(T1 v):                        tuple<T1,T2>
   _head(v)
                                       T1 _head
         tuple(T1 v, T2 v2):
           _head(v), tuple<T2>(v2)
We need a way to declare the type of the k-th element
     The get<N>() method will return it (later)


template <int, typename> struct tuple_elem;
template <typename T, typename... Ts>
struct tuple_elem<0, tuple<T,Ts...>> {
  typedef T type; //this is the head, base case
};
template <int k, typename T, typename Ts...>
struct tuple_elem<k, tuple<T,Ts...>> {
  typedef tuple_elem<k-1,Ts...>::type type; //recursion
};
template <int k, typename Ts...>
typename enable_if<k==0,
  typename tuple_elem<k,Ts...>::type&>::type
get(tuple<Ts...>& tuple) {
  return tuple._head;                            Why not a member
} //base case                                    function on tuple?

template <int k, typename T, typename Ts...>
typename enable_if<k!=0,
  typename tuple_elem<k,T,Ts...>::type&>::type
get(tuple<T,Ts...>& tuple) {
  tuple<Ts...>& base = tuple;
  get<k-1>(base); //recursion
}
tuple<int, float, string, employee> tup(...);
get<0>(tup) = 42;
get<3>(tup) = employee("John");
cout << get<3>(tup).name() << endl;

//Worth the effort. C# doesn’t have unlimited tuples!
//…and here’s another cool thing, Python-style:

tuple<int,bool> get_something() { ... }
                                           How does this work?
int number; bool flag;                     tuple<T1&,T2&,…>
std::tie(number, flag) = get_something();
//now number, flag are the unpacked tuple!
• Primary concern: improve compiler errors
   In file included from c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_tree.h:65:0,
               from c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/map:60,
               from ConceptsMotivation.cpp:2:
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = non_comparable]':
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_map.h:452:2: instantiated from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const
   key_type&) [with _Key = non_comparable, _Tp = int, _Compare = std::less<non_comparable>, _Alloc = std::allocator<std::pair<const non_comparable, int> >, std::map<_Key, _Tp, _Compare,
   _Alloc>::mapped_type = int, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = non_comparable]'
   ConceptsMotivation.cpp:8:20: instantiated from here
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h:236:22: error: no match for 'operator<' in '__x < __y'
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h:236:22: note: candidates are:
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_pair.h:207:5: note: template<class _T1, class _T2> bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&)
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_iterator.h:291:5: note: template<class _Iterator> bool std::operator<(const std::reverse_iterator<_Iterator>&, const
   std::reverse_iterator<_Iterator>&)
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_iterator.h:341:5: note: template<class _IteratorL, class _IteratorR> bool std::operator<(const std::reverse_iterator<_IteratorL>&, const
   std::reverse_iterator<_IteratorR>&)
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_tree.h:856:5: note: template<class _Key, class _Val, class _KeyOfValue, class _Compare, class _Alloc> bool std::operator<(const std::_Rb_tree<_Key,
   _Val, _KeyOfValue, _Compare, _Alloc>&, const std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>&)
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_map.h:894:5: note: template<class _Key, class _Tp, class _Compare, class _Alloc> bool std::operator<(const std::map<_Key, _Tp, _Compare, _Alloc>&,
   const std::map<_Key, _Tp, _Compare, _Alloc>&)
   c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_multimap.h:812:5: note: template<class _Key, class _Tp, class _Compare, class _Alloc> bool std::operator<(const std::multimap<_Key, _Tp, _Compare,
   _Alloc>&, const std::multimap<_Key, _Tp, _Compare, _Alloc>&)




• Secondary: optimizations, better specialization, etc.
• Future feature: NOT PART OF C++ 11
The language compiler verifies that the generic type
  performs only operations that are guaranteed to exist
  on its type parameters
     Limited set of constraints: base class, interface,
     parameterless constructor

class SortedList<T> where T : IComparable<T> {
  private T[] items;
  public void Add(T item) {
    //...can use item.CompareTo(otherItem) here
  }
}
New keyword (concept)
  Looks like a template class with no implementation

auto concept CopyConstructible<typename T> {
  T(const T&);
};
auto concept Comparable<typename T> {
  bool operator<(T, T);
};
auto concept Convertible<typename T, typename S> {
  operator S(const T&);
};
To assert that a concept is available, use requires
  Can specialize templates on concept requirements


template <typename T> requires LessThanComparable<T>
void sort(T* data, int length) { ... }

//instead of SFINAE:
template <typename T>
  requires !LessThanComparable<T> && GreaterThanComparable<T>
void sort(T* data, int length) { ... }
Concepts can require other concepts
  Concepts can derive from other concepts

concept InputIterator<typename Iter, typename Elem> {
   requires CopyConstructible<Iter>;
   Elem operator*(const Iter&);
   Iter operator++(Iter&, int);
};
concept ForwardIterator<typename Iter, typename Elem>
   : InputIterator<Iter, Value> {
   //additional requirements
};
Specify how to bind a concept to an existing type
     E.g., vector<T> was not designed to adhere to a stack
     concept, but can be adapted after the fact

concept stack<typename C, typename T> {
  void push(C&, const T&);
  bool pop(C&, T&);
};
template <typename T> concept_map stack<vector<T>> {
  void push(vector<T>& v, const T& t) { v.push_back(t); }
  bool pop(vector<T>& v, T& t) { ... }
};
• enable_if “[…] is marred by a baroque syntax,
  frequent and nontrivial corner cases, and interference
  of mechanism with the exposed interface.”
   – N3329 (draft proposal for static_if)
• Currently impossible to:
   – Define a class member conditionally
   – Easily share code between specializations
   – Mix case-specific code within the same function
template <typename T>
void print(const T& t) {
  static_if (is_integral<T>::value) {
    printf("%d", (unsigned long long)t);
  } else {
    static_if (is_pointer<T>::value) {
      printf("%p", t);
    }
    else {
      static_assert(false, "Unsupported type");
    }
  }
}
template <int N>
struct factorial { //remember fibo?
  static_if (N <= 1) {
    enum { value = 1 };
  } else {
    enum { value = factorial<N-1>::value * N };
  }
};

//can replace many uses of concepts:
template <typename T> void sort(...)
if (has_operator_less_than<T>::value) { ... }
Proposal N3361 based on Intel Cilk
  cilk_spawn, cilk_sync, cilk_for keywords
     Akin to similar OpenMP pragmas
     Additional suggestions for SIMD-friendly operators, such as
     array slices and #pragma simd

cilk_for (auto c = customers.begin();
          c != customers.end(); ++c) {
  consider_vip_status(c);
  adjust_discount(c);
}
Mirroring the success of C# 5’s await operator
  Breaks down the method into a synchronous part and
  one or more continuations
future<vector<image*>> download_profile_images(
                              vector<user> users) {
  vector<image*> images;
  webclient wc;
  for (const auto& user : users)
    images.push_back(new image(
      await wc.download(user.profile_image_url()));
  return images;
}
Transactional language constructs on top of software
  transactional memory (N3341)
     (By the way, Intel Haswell will have hardware TX semantics)

class Account {
  void withdraw(int amount) {
    __transaction { balance -= amount; }
  }
};
void transfer(Account& a, Account& b, int amount) {
  __transaction {
    a.withdraw(amount); b.deposit(amount);
  }
}
Variadic Templates
Concepts
Other Wild Ideas
Many more at the ISO C++ WG
SELA software: Variadic Templates and Concepts

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
C++11
C++11C++11
C++11
 
C++ references
C++ referencesC++ references
C++ references
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
02basics
02basics02basics
02basics
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
C++11
C++11C++11
C++11
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C++ 11
C++ 11C++ 11
C++ 11
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
oop Lecture 17
oop Lecture 17oop Lecture 17
oop Lecture 17
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 

Destaque

Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web ApplicationsSasha Goldshtein
 
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...Alex Choroshin
 
Caching in Windows Azure
Caching in Windows AzureCaching in Windows Azure
Caching in Windows AzureIdo Flatow
 
What's New in WCF 4.5
What's New in WCF 4.5What's New in WCF 4.5
What's New in WCF 4.5Ido Flatow
 
Automating Windows Azure
Automating Windows AzureAutomating Windows Azure
Automating Windows AzureIdo Flatow
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF WorkshopIdo Flatow
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...Seok-joon Yun
 
Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web ApplicationsSasha Goldshtein
 
Debugging with Fiddler
Debugging with FiddlerDebugging with Fiddler
Debugging with FiddlerIdo Flatow
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Anil Bapat
 
IIS for Developers
IIS for DevelopersIIS for Developers
IIS for DevelopersIdo Flatow
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 

Destaque (16)

Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web Applications
 
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...
Creating Facebook Canvas Apps Using The New Template And Library For ASP.NET ...
 
Caching in Windows Azure
Caching in Windows AzureCaching in Windows Azure
Caching in Windows Azure
 
What's New in WCF 4.5
What's New in WCF 4.5What's New in WCF 4.5
What's New in WCF 4.5
 
Automating Windows Azure
Automating Windows AzureAutomating Windows Azure
Automating Windows Azure
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web Applications
 
Debugging with Fiddler
Debugging with FiddlerDebugging with Fiddler
Debugging with Fiddler
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++
 
IIS for Developers
IIS for DevelopersIIS for Developers
IIS for Developers
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 

Semelhante a SELA software: Variadic Templates and Concepts

Semelhante a SELA software: Variadic Templates and Concepts (20)

2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
C++ metaprogramming
C++ metaprogrammingC++ metaprogramming
C++ metaprogramming
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
C++ metaprogramming
C++ metaprogrammingC++ metaprogramming
C++ metaprogramming
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Templates2
Templates2Templates2
Templates2
 
Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile Time
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)Milot Shala - C++ (OSCAL2014)
Milot Shala - C++ (OSCAL2014)
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
Templates
TemplatesTemplates
Templates
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
 
Namespaces
NamespacesNamespaces
Namespaces
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
 

Mais de Sasha Goldshtein

Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing LandscapeSasha Goldshtein
 
The Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerThe Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerSasha Goldshtein
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF AbyssSasha Goldshtein
 
Visual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkVisual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkSasha Goldshtein
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSasha Goldshtein
 
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinC# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinSasha Goldshtein
 
Modern Backends for Mobile Apps
Modern Backends for Mobile AppsModern Backends for Mobile Apps
Modern Backends for Mobile AppsSasha Goldshtein
 
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Sasha Goldshtein
 
Mastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionMastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionSasha Goldshtein
 
Delivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesDelivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesSasha Goldshtein
 
Building Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendBuilding Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendSasha Goldshtein
 
Building iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesBuilding iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesSasha Goldshtein
 
Windows Azure Mobile Services
Windows Azure Mobile ServicesWindows Azure Mobile Services
Windows Azure Mobile ServicesSasha Goldshtein
 
First Steps in Android Development
First Steps in Android DevelopmentFirst Steps in Android Development
First Steps in Android DevelopmentSasha Goldshtein
 
First Steps in iOS Development
First Steps in iOS DevelopmentFirst Steps in iOS Development
First Steps in iOS DevelopmentSasha Goldshtein
 
JavaScript, Meet Cloud: Node.js on Windows Azure
JavaScript, Meet Cloud: Node.js on Windows AzureJavaScript, Meet Cloud: Node.js on Windows Azure
JavaScript, Meet Cloud: Node.js on Windows AzureSasha Goldshtein
 

Mais de Sasha Goldshtein (20)

Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing Landscape
 
The Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerThe Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF Primer
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF Abyss
 
Visual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkVisual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET Framework
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS X
 
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinC# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
 
Modern Backends for Mobile Apps
Modern Backends for Mobile AppsModern Backends for Mobile Apps
Modern Backends for Mobile Apps
 
.NET Debugging Workshop
.NET Debugging Workshop.NET Debugging Workshop
.NET Debugging Workshop
 
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
 
Mastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionMastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and Production
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
State of the Platforms
State of the PlatformsState of the Platforms
State of the Platforms
 
Delivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesDelivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in Minutes
 
Building Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendBuilding Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET Backend
 
Building iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesBuilding iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile Services
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
Windows Azure Mobile Services
Windows Azure Mobile ServicesWindows Azure Mobile Services
Windows Azure Mobile Services
 
First Steps in Android Development
First Steps in Android DevelopmentFirst Steps in Android Development
First Steps in Android Development
 
First Steps in iOS Development
First Steps in iOS DevelopmentFirst Steps in iOS Development
First Steps in iOS Development
 
JavaScript, Meet Cloud: Node.js on Windows Azure
JavaScript, Meet Cloud: Node.js on Windows AzureJavaScript, Meet Cloud: Node.js on Windows Azure
JavaScript, Meet Cloud: Node.js on Windows Azure
 

Último

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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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...
 
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...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

SELA software: Variadic Templates and Concepts

  • 1. © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel www.sela.co.il
  • 3. • Visual Studio 2010: Some features are supported • Visual Studio 2012: Some more features are supported Not supported yet Visual Studio 2012 Visual Studio 2010 Automatic Concurrency Variadic variables, library templates decltype Memory Custom Rvalue model literals references Delegating Lambda constructors functions • Comparison chart between many other compilers: http://s.sashag.net/rpST0u
  • 4. The problem with existing templates is that the number of parameters is constant, consider: tuple, printf, other type-safe va_list, … template <typename T1> struct tuple { T1 first; }; template <typename T1, typename T2> struct tuple { T1 first; T2 second; }; template <typename T1, typename T2, typename T3> struct tuple { T1 first; T2 second; T3 third; }; //VC11 <tuple> does this with macros, going up to 10 parameters
  • 5. New syntax for unbounded type parameter lists and function parameter lists “Dot-dot-dot is where the fun begins” template <typename... Ts> void foo(Ts&&... vs); //note: Ts is NOT a type, vs is NOT a variable foo(42); foo(5, "Hello, World", vector<int>()); template <typename... Ts> struct tuple; //requires some serious work! tuple<int, float, string> tup(42, 42.0f, "42"); get<1>(tup) += 3.0f; cout << get<2>(tup) << endl;
  • 6. New syntax for type list expansion …and there’s also a new operator: sizeof...() template <typename... Ts> int passthrough_printf(const char* fmt, Ts&&... vs) return printf(fmt, vs...); } template <typename... Ts> class mixin : public Ts... {}; //will inherit from all Ts specified //note: the following two statements ARE NOT THE SAME! foo(goo(vs...)); ≡ foo(goo(v1, v2, v3)); foo(goo(vs)...); ≡ foo(goo(v1), goo(v2), goo(v3));
  • 7. Typically, you have a base case that does something (or nothing) and “recurse” to it from the variadic case Not true recursion (different template) template <typename... Ts> void print(Ts&&... vs) {} //base case, will match empty list, do nothing template <typename T, typename... Ts> void print(T&& v, Ts&&... vs) { cout << v << endl; print(vs...); //”recursive” case; note that any decent compiler } //will inline the whole thing into the caller
  • 8. Alternatively, the base case can be a bounded number of parameters to which we “recurse” template <typename T1, typename T2> bool assertContained(T1&& v1, T2&& v2) { return v1 == v2; } template <typename T1, typename T2, typename... Ts> bool assertContained(T1&& v1, T2&& v2, Ts&&... vs) { return (v1 == v2 || assertContained(v1, vs...)); }
  • 9. Using the compiler’s template mechanism to do work at compile-time Theorem: C++ templates are Turing-complete //recursive case: template <int N> struct fibo { static const int value = fibo<N-1>::value + fibo<N-2>::value; }; //base cases: template <> struct fibo<0> { static const int value = 1; }; template <> struct fibo<1> { static const int value = 1; }; cout << fibo<14>::value; //compile-time!
  • 10. template <typename T> void print(const T& t) {} template <typename T> void print(const T& t, typename enable_if< is_pointer<T>::value, void* >::type dummy = nullptr) { From <type_traits> printf("%p", t); (simple specializations) } template <typename T> void print(const T& t, typename enable_if< is_convertible<T,string>::value, void* template < bool, typename T = void >::type dummy = nullptr) { > printf("%s", string(t).c_str()); struct enable_if {}; } template <typename T> struct enable_if<true,T> { typedef T type; };
  • 11. We now develop a partial tuple<...> (Practically) No limit on number of type parameters Following A. Alexandrescu’s GoingNative 2012 talk template <typename... Ts> struct tuple {}; template <typename T, typename... Ts> struct tuple : private tuple<Ts...> { T _head; public: tuple(T&& v, Ts&&... vs) : _head(v), tuple<Ts...>(vs...) {} //many more methods omitted };
  • 12. • Note that tuple<T1,T2> derives from tuple<T2> tuple<> tuple<> tuple<> (empty) (empty) (empty) tuple<T1> tuple<T2> T1 _head T2 _head tuple(T1 v): tuple<T1,T2> _head(v) T1 _head tuple(T1 v, T2 v2): _head(v), tuple<T2>(v2)
  • 13. We need a way to declare the type of the k-th element The get<N>() method will return it (later) template <int, typename> struct tuple_elem; template <typename T, typename... Ts> struct tuple_elem<0, tuple<T,Ts...>> { typedef T type; //this is the head, base case }; template <int k, typename T, typename Ts...> struct tuple_elem<k, tuple<T,Ts...>> { typedef tuple_elem<k-1,Ts...>::type type; //recursion };
  • 14. template <int k, typename Ts...> typename enable_if<k==0, typename tuple_elem<k,Ts...>::type&>::type get(tuple<Ts...>& tuple) { return tuple._head; Why not a member } //base case function on tuple? template <int k, typename T, typename Ts...> typename enable_if<k!=0, typename tuple_elem<k,T,Ts...>::type&>::type get(tuple<T,Ts...>& tuple) { tuple<Ts...>& base = tuple; get<k-1>(base); //recursion }
  • 15. tuple<int, float, string, employee> tup(...); get<0>(tup) = 42; get<3>(tup) = employee("John"); cout << get<3>(tup).name() << endl; //Worth the effort. C# doesn’t have unlimited tuples! //…and here’s another cool thing, Python-style: tuple<int,bool> get_something() { ... } How does this work? int number; bool flag; tuple<T1&,T2&,…> std::tie(number, flag) = get_something(); //now number, flag are the unpacked tuple!
  • 16. • Primary concern: improve compiler errors In file included from c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_tree.h:65:0, from c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/map:60, from ConceptsMotivation.cpp:2: c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = non_comparable]': c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_map.h:452:2: instantiated from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = non_comparable, _Tp = int, _Compare = std::less<non_comparable>, _Alloc = std::allocator<std::pair<const non_comparable, int> >, std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = non_comparable]' ConceptsMotivation.cpp:8:20: instantiated from here c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h:236:22: error: no match for 'operator<' in '__x < __y' c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_function.h:236:22: note: candidates are: c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_pair.h:207:5: note: template<class _T1, class _T2> bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_iterator.h:291:5: note: template<class _Iterator> bool std::operator<(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&) c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_iterator.h:341:5: note: template<class _IteratorL, class _IteratorR> bool std::operator<(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&) c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_tree.h:856:5: note: template<class _Key, class _Val, class _KeyOfValue, class _Compare, class _Alloc> bool std::operator<(const std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>&, const std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>&) c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_map.h:894:5: note: template<class _Key, class _Tp, class _Compare, class _Alloc> bool std::operator<(const std::map<_Key, _Tp, _Compare, _Alloc>&, const std::map<_Key, _Tp, _Compare, _Alloc>&) c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_multimap.h:812:5: note: template<class _Key, class _Tp, class _Compare, class _Alloc> bool std::operator<(const std::multimap<_Key, _Tp, _Compare, _Alloc>&, const std::multimap<_Key, _Tp, _Compare, _Alloc>&) • Secondary: optimizations, better specialization, etc. • Future feature: NOT PART OF C++ 11
  • 17. The language compiler verifies that the generic type performs only operations that are guaranteed to exist on its type parameters Limited set of constraints: base class, interface, parameterless constructor class SortedList<T> where T : IComparable<T> { private T[] items; public void Add(T item) { //...can use item.CompareTo(otherItem) here } }
  • 18. New keyword (concept) Looks like a template class with no implementation auto concept CopyConstructible<typename T> { T(const T&); }; auto concept Comparable<typename T> { bool operator<(T, T); }; auto concept Convertible<typename T, typename S> { operator S(const T&); };
  • 19. To assert that a concept is available, use requires Can specialize templates on concept requirements template <typename T> requires LessThanComparable<T> void sort(T* data, int length) { ... } //instead of SFINAE: template <typename T> requires !LessThanComparable<T> && GreaterThanComparable<T> void sort(T* data, int length) { ... }
  • 20. Concepts can require other concepts Concepts can derive from other concepts concept InputIterator<typename Iter, typename Elem> { requires CopyConstructible<Iter>; Elem operator*(const Iter&); Iter operator++(Iter&, int); }; concept ForwardIterator<typename Iter, typename Elem> : InputIterator<Iter, Value> { //additional requirements };
  • 21. Specify how to bind a concept to an existing type E.g., vector<T> was not designed to adhere to a stack concept, but can be adapted after the fact concept stack<typename C, typename T> { void push(C&, const T&); bool pop(C&, T&); }; template <typename T> concept_map stack<vector<T>> { void push(vector<T>& v, const T& t) { v.push_back(t); } bool pop(vector<T>& v, T& t) { ... } };
  • 22. • enable_if “[…] is marred by a baroque syntax, frequent and nontrivial corner cases, and interference of mechanism with the exposed interface.” – N3329 (draft proposal for static_if) • Currently impossible to: – Define a class member conditionally – Easily share code between specializations – Mix case-specific code within the same function
  • 23. template <typename T> void print(const T& t) { static_if (is_integral<T>::value) { printf("%d", (unsigned long long)t); } else { static_if (is_pointer<T>::value) { printf("%p", t); } else { static_assert(false, "Unsupported type"); } } }
  • 24. template <int N> struct factorial { //remember fibo? static_if (N <= 1) { enum { value = 1 }; } else { enum { value = factorial<N-1>::value * N }; } }; //can replace many uses of concepts: template <typename T> void sort(...) if (has_operator_less_than<T>::value) { ... }
  • 25. Proposal N3361 based on Intel Cilk cilk_spawn, cilk_sync, cilk_for keywords Akin to similar OpenMP pragmas Additional suggestions for SIMD-friendly operators, such as array slices and #pragma simd cilk_for (auto c = customers.begin(); c != customers.end(); ++c) { consider_vip_status(c); adjust_discount(c); }
  • 26. Mirroring the success of C# 5’s await operator Breaks down the method into a synchronous part and one or more continuations future<vector<image*>> download_profile_images( vector<user> users) { vector<image*> images; webclient wc; for (const auto& user : users) images.push_back(new image( await wc.download(user.profile_image_url())); return images; }
  • 27. Transactional language constructs on top of software transactional memory (N3341) (By the way, Intel Haswell will have hardware TX semantics) class Account { void withdraw(int amount) { __transaction { balance -= amount; } } }; void transfer(Account& a, Account& b, int amount) { __transaction { a.withdraw(amount); b.deposit(amount); } }
  • 28. Variadic Templates Concepts Other Wild Ideas Many more at the ISO C++ WG

Notas do Editor

  1. Not supported by VC11.To show the demo, use MinGW or any other gcc-clone (gcc 4.6.2 or higher is known to work).The quote (“dot dotdot is where the fun begins”) is from Andrei Alexandrescu’s talk at GoingNative 2012: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic
  2. This is not up to date with the most recent proposal: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf