SlideShare a Scribd company logo
1 of 54
Download to read offline
C++17 and Beyond
A Glimpse at the C++ of Tomorrow
Andreas Weis
Munich C++ User Group, October 2016
Big Features and Small Features
Bjarne talked a lot about upcoming features in his
CppCon keynote 1
For Bjarne, a big feature is one that changes how we think
about programs.
C++11 was a release with big features (Lambdas, Move
Semantics, Variadic Templates, . . . ), C++14 had mostly
small features.
The hope for C++17 was to again get big features. But it
looks like none of them will make it into the standard in time.
1
https://www.youtube.com/watch?v=_wzc7a3McOs
Outline
This talk tries to focus on the big features.
We will not discuss C++17 only, but also some of the
features that are currently specified as a TS.
Still, there’s lots of stuff that we won’t talk about.
For a complete list of what’s new in C++17, check out
Alisdair Meredith’s CppCon talk C++17 in Breadth (Not
Depth)2
Feel free to disagree on whether the features discussed here
will have a major impact.
2
https://www.youtube.com/watch?v=22jIHfvelZk
if constexpr
Basically a smarter #if
Goes back to proposal N3329 from 2012, heavily inspired by
D’s static if (introduced there in 2005)3
Was held back because of concerns about overlap with
Concepts and uncertainty about scoping
Re-proposed as if constexpr in 2016 (after Concepts Lite),
with slightly different semantics
3
see also Alexandrescu’s Going Native 2012 talk Static if I had a hammer
Compile time branching is weird
template <class T>
struct is_awesome;
template <class T>
void compute_stuff ()
{
if(is_awesome <T>:: value) {
// awesome algorithm
// ...
} else {
// slightly less awesome algorithm
// ...
}
}
Compile time branching is weird
Compiler will (insistently) warn that you are branching on a
compile-time constant condition.
Both branches need to compile for all valid Ts.
Runtime branching does not cut it. What we really want is
conditional compilation.
SFINAE to the rescue!
template <class T>
std:: enable_if_t <is_awesome <T>:: value >
compute_stuff ()
{
// awesome algorithm
// ...
}
template <class T>
std:: enable_if_t <! is_awesome <T>:: value >
compute_stuff ()
{
// slightly less awesome algorithm
// ...
}
SFINAE to the rescue?
Lots of boilerplate and code duplication.
Requires intimate knowledge of what many consider a weird
corner case of C++ templates.
std::enable if makes stuff easier, but is still prone to
breaking in non-obious ways.
if constexpr
template <class T>
void compute_stuff ()
{
if constexpr(is_awesome <T>:: value) {
// awesome algorithm
// ...
} else {
// slightly less awesome algorithm
// ...
}
}
The discarded branch is not instantiated by the compiler.
Otherwise behaves like a regular if statement.
if constexpr
This is less powerful than the initial static if idea, which
was much closer to #if than to if.
No branching at global or namespace scope.
No layout changes.
if constexpr introduces new scope.
Compiler support for if constexpr
Only gcc 7 and clang 3.9 support it already.
if and switch with initializer
void safe_init () {
{
std:: lock_guard <std::mutex > lk(mx_);
if(v.empty ()) {
v.push_back(kInitialValue );
}
}
// ...
}
Need an additional pair of {}s for scoping lock
When refactoring, take care that the if cannot be separated
from the lock
if and switch with initializer
void safe_init () {
if(std:: lock_guard <std::mutex > lk(mx_);
v.empty ()) {
v.push_back(kInitialValue );
}
// ...
}
lk is scoped by the if.
if and switch with initializer
if(auto p = m.try_emplace(key , value );
!p.second)
{
FATAL("Element already registered");
} else {
process(p.second );
}
Avoids polluting the enclosing namespace with identifiers.
Compiler support for if and switch with initializer
Only gcc 7 and clang 3.9 support it already.
Structured Bindings
std::tie is not as useful as it should be:
std::map <std::string , int > my_map;
auto const ret = my_map.insert ({"key", 42});
std::map <std::string , int >:: iterator it;
bool was_inserted;
std::tie(it , was_inserted) = ret;
We lose type deduction for the iterator type.
We lose the const qualifier.
Separate declaration often not feasible for non-trivial types.
Structured Bindings - To the rescue!
std::map <std::string , int > my_map;
auto const [it , was_inserted] =
my_map.insert ({"key", 42});
Structured Bindings - Destructuring
But wait, there’s more:
struct Foo {
int i;
float f;
std:: string s;
};
Foo f;
// ...
auto [natural , real , text] = f;
Structured Bindings
Alright, cool. But how is this a major feature?
Some preliminary boilerplate...
struct any_type {
template <class T>
constexpr operator T(); // non explicit
};
template <class T, class ... TArgs >
class is_braces_constructible ;
// std:: true_type if we can construct
// a T from the TArgs
Struct to tuple
template <class T> auto to_tuple(T&& object) {
using type = std:: decay_t <T>;
if constexpr( is_braces_constructible
<type , any_type , any_type >{})
{
auto && [p1 , p2] = object;
return std:: make_tuple(p1 , p2);
} else if constexpr( is_braces_constructible
<type , any_type >{})
{
auto && [p1] = object;
return std:: make_tuple(p1);
} else {
return std:: make_tuple ();
}
}
Simple compile-time reflection
Full example at
https://www.reddit.com/r/cpp/comments/4yp7fv/c17_
structured_bindings_convert_struct_to_a_tuple/.
Once we have tuples, we can do all kinds of
metaprogramming (see Boost Hana)
Not clear how much benefit structured bindings really bring,
but chances are they will turn out more powerful than they
seem at first glance.
Structured bindings + if with initializer
std::map <std::string , int > my_map;
if(auto const [it , was_inserted] =
my_map.insert ({"key", 42});
!was_inserted)
{
throw InsertionFailed ();
}
Compiler support for structured bindings
Only (partially) supported in Clang 4.0 today.
Concepts TS (not part of C++17)
Specify constraints for template arguments.
template <typename T>
T const& min(T const& a, T const& b)
{
return (a < b) ? a : b;
}
Concepts Example
template <typename T>
concept bool LTComparable = requires(T a, T b)
{
{ a < b } -> bool;
};
template <LTComparable T>
T const& min(T const& a, T const& b)
{
return (a < b) ? a : b;
}
Error messages with concepts
Here’s what happens if we try to use min with a type Foo that
does not have operator<:
In function ’int main ()’:
error: cannot call function ’const T& min(const T&, const T&) [with T = Foo]’
std :: cout << min(a, b) << std :: endl;
^
note: constraints not satisfied
T const& min(T const& a, T const& b)
^~~
note: within ’template <class T> concept const bool LTComparable <T> [with T = Foo]’
concept bool LTComparable = requires(T a, T b) {
^~~~~~~~~~~~
note: with ’Foo a’
note: with ’Foo b’
note: the required expression ’(a < b)’ would be ill -formed
Error messages with concepts
Here’s what happens if there is an operator<, but it does not
return bool:
In function ’int main ()’:
error: cannot call function ’const T& min(const T&, const T&) [with T = Foo]’
std :: cout << min(a, b) << std :: endl;
^
note: constraints not satisfied
T const& min(T const& a, T const& b)
^~~
note: within ’template <class T> concept const bool LTComparable <T> [with T = Foo]’
concept bool LTComparable = requires(T a, T b) {
^~~~~~~~~~~~
note: with ’Foo a’
note: with ’Foo b’
note: ’operator <(a, b)’ is not implicitly convertible to ’bool ’
Concepts
Concepts are not checked for completeness. The
implementation may use a concept parameter like any
typename.
template <LTComparable T>
T const& max(T const& a, T const& b)
{
return (a > b) ? a : b;
}
Constraints can be used instead of SFINAE to remove
functions from the overload set.
template <typename T>
requires std:: is_integral <T>:: value
void ints_only(T i);
Writing concepts
Defining good concepts is non-trivial. Concepts are
meant to represent fundamental concepts in an
application domain (hence the name ”concepts”).
Similarly throwing together a set of syntactic constraints
to be used for a the arguments for a single class or
algorithm is not what concepts were designed for and will
not give the full benefits of the mechanism.
From the C++ Core Guidelines 4
4
https://github.com/isocpp/CppCoreGuidelines/blob/master/
CppCoreGuidelines.md#
t20-avoid-concepts-without-meaningful-semantics
Writing concepts
In the current TS, concepts only allow checking syntactical
properties.
However, concepts should only be designed from meaningful
semantics (potentially including space/time complexity).
Unfortunately, we cannot have non-trivial semantics without
proofs.
Concepts0x approximated proofs with axioms, in Concepts
Lite they are gone completely.
Writing concepts
Do not be mislead by the current feature state concepts!
Concepts are not about syntax.
Always design your concepts on paper from clear, logical
semantics.
Then try to identify the parts that overlap with what the
compiler can check.
Take the compiler’s help where you can get it. Document the
rest.
Important is not how much support you get from the
compiler, but how you think about your code.
Thinking about concepts
Alex Stepanov’s books 5
Take a look at functional programming
5
If you have only time for one, choose the one on the right
Compiler support for concepts
Currently only on gcc 6.1 with -fconcepts
Stepanov-style concepts
#if !defined __cpp_concepts || 
__cpp_concepts < 201507
# define LTComparable typename
#endif
template <LTComparable T>
T const& min(T const& a, T const& b);
Library Time!
Vocabulary Types - std::optional
std:: optional <Value > readValue ();
// ...
auto const v = readValue ();
if(v) { useValue (*v); }
useValue(v.value_or(default_value ));
Constructing std::optional
auto empty = std:: optional <Value >();
auto also_empty = std:: optional(std:: nullopt );
auto def_constr = std:: make_optional <Value >();
auto value = std:: make_optional(v);
auto from_args =
std:: make_optional <Value >(arg1 , arg2 );
auto from_init_list =
std:: make_optional <std::vector <int >>
({1 ,2 ,3 ,4 ,5});
Compiler support for std::optional
Supported in clang 4, gcc 7 and VC 15.
Also: Boost.Optional in Boost 1.30 with slightly different
interface.
Vocabulary Types - std::variant
std:: variant <int , float , std::string > v = 42;
int n = std::get <int >(v);
v = std:: string("Narf");
std:: string s = std::get <std::string >(v);
float f = std::get <float >(v);
// throws std:: bad_variant_access
Polymorphism with variants
struct Circle { float getArea () const; };
struct Square { float getArea () const; };
struct Triangle { float getArea () const; };
typedef variant <Circle , Square , Triangle > Shape;
struct GetShapeAreaVisitor {
template <typename T>
float operator ()(T const& s) {
return s.getArea ();
}
};
float getArea(Shape const& s) {
return std:: visit( GetShapeAreaVisitor {}, s);
}
Variant details
std::variant is almost-never-empty.
A variant always holds an instance of one of its Ts.
If a type-changing assignment throws, variant might have to
revert to a special valueless state
valueless by exception().
In the absence of exceptions, variants give the never-empty
guarantee.
Supported in gcc 7 and VC 15.
Available with slightly different interface and semantics in
Boost 1.31.
Vocabulary Types - std::any
std::any any_value;
assert (! any_value.has_value ());
any_value = std:: make_any <std::string >("narf");
any_value = std:: make_any <int >(42);
int i = std:: any_cast <int >( any_value );
auto* is_null =
std:: any_cast <std::string >(& any_value );
std:: any_cast <std::string >( any_value );
// throws std:: bad_any_cast
Details of std::any
Prefer std::variant, if possible.
Type-erasure in std::any requires heap allocation.
Little better than a void*.
Supported in gcc 7, clang 4 and VC 15.
Available in Boost 1.23 with slightly different interface.
Vocabulary Types - std::string view
void processString(char const* str);
// loses length
void processString(std:: string const& str);
// might make a copy
void processString(char const* str ,
std:: size_t len);
// yuck!
Vocabulary Types - std::string view
void processString(std:: string_view const& str);
Details of std::string view
A non-owning view on an immutable string.
Implemented as a std::basic string view template,
similar to std::string.
Can be constructed from a std::string or a const pointer.
When constructing from pointer, if no length is given, string
must be null-terminated and length will be computed at
construction.
Constructing views on a substring requires no copy.
Supported in gcc 7, clang 4 and VC 15.
Available in the GSL
(https://github.com/Microsoft/GSL)
Ranges TS (not part of C++17)
The STL achieves great things by separating algorithms from
data structures through iterators.
But iterators can be awkward to use.
c.erase(remove_if(begin(c), end(c), pred),
end(c));
Ranges consists of two parts:
An STL-like library that is based on ranges instead of iterators.
Works with the existing STL containers.
Concepts for both the classic STL and the new ranges parts
Sentinels
Iterators point to elements.
A range in STL is spanned by an iterator to the first element
and an iterator to one-past-the-last.
Except that end iterator might not really point to anything. If
we are dealing with a range where not all elements are stored
in memory, obtaining and end iterator might actually require
iterating the whole range.
Ranges introduces the notion of a sentinel.
A sentinel can be compared to an iterator. Both are equal if
the iterator points to the end element.
A range in ranges is spanned by an iterator and a sentinel.
What is a range?
Something that you can call begin and end on.
template <class T>
using iterator_t =
decltype(ranges :: begin(declval <T& >()));
template <class T>
using sentinel_t =
decltype(ranges ::end(declval <T& >()));
template <class T>
concept bool Range () {
return requires {
typename sentinel_t <T>;
};
};
Ranges - Actions
In-place mutation.
Composable.
action :: remove_if(c, pred );
Pipe syntax:
vi = std:: move(vi) |
action :: sort |
action :: unique;
Ranges - Views
Non-mutating, lazy sequence manipulation.
Composable.
Cheap to create and copy.
auto odd = []( int i){ return i % 2 == 1; };
auto to_str = []( int i){
return std:: to_string(i);}
using namespace ranges;
std::vector <int > vi = view :: ints (1 ,11);
// vi = {1,2,3,4,5,6,7,8,9,10};
auto rng = vi | view :: remove_if(odd)
| view :: transform(to_str );
// rng == {"2" ,"4" ,"6" ,"8" ,"10"};
Ranges - Compiler support
You can use ranges today!
Reference implementation range-v36 works on gcc 4.8.5,
clang 3.5.2; Microsoft offers a fork that works on VC 147
Full experience requires concepts language support by the
compiler, but even without that it’s a pretty great library.
Also: If you find bugs in the TS spec now, it is way easier to
fix than once it goes IS.
6
https://github.com/ericniebler/range-v3
7
github.com/microsoft/Range-V3-VS2015
Wrapping up...
Lots of features are available for use already today, especially
from the library.
Small features can make a big difference in everyday work.
Other features might be bigger than they seem at first.
Don’t let lack of compiler support keep you from changing
how you think about your code today.
Thanks for your attention.

More Related Content

What's hot

C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersRichard Thomson
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsAndrey Upadyshev
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...Andrey Upadyshev
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview QuestionsGradeup
 
Lec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptLec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptRushdi Shams
 

What's hot (20)

C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Modern C++
Modern C++Modern C++
Modern C++
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
C++11
C++11C++11
C++11
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
 
What is c
What is cWhat is c
What is c
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
Lec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptLec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory Concept
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Strings
StringsStrings
Strings
 

Viewers also liked

C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/Sławomir Zborowski
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Sławomir Zborowski
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolRandy Connolly
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin UpadhyayBipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol BasicChuong Mai
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Rodolfo Kohn
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11Uilian Ries
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 Sumant Tambe
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassYogendra Rampuria
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesSami Mut
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointerschchwy Chang
 

Viewers also liked (20)

C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/
 
Presentation
PresentationPresentation
Presentation
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
 
TCP/IP
TCP/IPTCP/IP
TCP/IP
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol
 
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13
 
C++11
C++11C++11
C++11
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
C++14 Overview
C++14 OverviewC++14 Overview
C++14 Overview
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 

Similar to Cpp17 and Beyond

Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifestohu hans
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++PVS-Studio
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in goborderj
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
 
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
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verQrembiezs Intruder
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6BlackRabbitCoder
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Ali Aminian
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_iNico Ludwig
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++TemplatesGanesh Samarthyam
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0xppd1961
 

Similar to Cpp17 and Beyond (20)

Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
C tutorials
C tutorialsC tutorials
C tutorials
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
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
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 

Recently uploaded

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 

Recently uploaded (20)

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 

Cpp17 and Beyond

  • 1. C++17 and Beyond A Glimpse at the C++ of Tomorrow Andreas Weis Munich C++ User Group, October 2016
  • 2. Big Features and Small Features Bjarne talked a lot about upcoming features in his CppCon keynote 1 For Bjarne, a big feature is one that changes how we think about programs. C++11 was a release with big features (Lambdas, Move Semantics, Variadic Templates, . . . ), C++14 had mostly small features. The hope for C++17 was to again get big features. But it looks like none of them will make it into the standard in time. 1 https://www.youtube.com/watch?v=_wzc7a3McOs
  • 3. Outline This talk tries to focus on the big features. We will not discuss C++17 only, but also some of the features that are currently specified as a TS. Still, there’s lots of stuff that we won’t talk about. For a complete list of what’s new in C++17, check out Alisdair Meredith’s CppCon talk C++17 in Breadth (Not Depth)2 Feel free to disagree on whether the features discussed here will have a major impact. 2 https://www.youtube.com/watch?v=22jIHfvelZk
  • 4. if constexpr Basically a smarter #if Goes back to proposal N3329 from 2012, heavily inspired by D’s static if (introduced there in 2005)3 Was held back because of concerns about overlap with Concepts and uncertainty about scoping Re-proposed as if constexpr in 2016 (after Concepts Lite), with slightly different semantics 3 see also Alexandrescu’s Going Native 2012 talk Static if I had a hammer
  • 5. Compile time branching is weird template <class T> struct is_awesome; template <class T> void compute_stuff () { if(is_awesome <T>:: value) { // awesome algorithm // ... } else { // slightly less awesome algorithm // ... } }
  • 6. Compile time branching is weird Compiler will (insistently) warn that you are branching on a compile-time constant condition. Both branches need to compile for all valid Ts. Runtime branching does not cut it. What we really want is conditional compilation.
  • 7. SFINAE to the rescue! template <class T> std:: enable_if_t <is_awesome <T>:: value > compute_stuff () { // awesome algorithm // ... } template <class T> std:: enable_if_t <! is_awesome <T>:: value > compute_stuff () { // slightly less awesome algorithm // ... }
  • 8. SFINAE to the rescue? Lots of boilerplate and code duplication. Requires intimate knowledge of what many consider a weird corner case of C++ templates. std::enable if makes stuff easier, but is still prone to breaking in non-obious ways.
  • 9. if constexpr template <class T> void compute_stuff () { if constexpr(is_awesome <T>:: value) { // awesome algorithm // ... } else { // slightly less awesome algorithm // ... } } The discarded branch is not instantiated by the compiler. Otherwise behaves like a regular if statement.
  • 10. if constexpr This is less powerful than the initial static if idea, which was much closer to #if than to if. No branching at global or namespace scope. No layout changes. if constexpr introduces new scope.
  • 11. Compiler support for if constexpr Only gcc 7 and clang 3.9 support it already.
  • 12. if and switch with initializer void safe_init () { { std:: lock_guard <std::mutex > lk(mx_); if(v.empty ()) { v.push_back(kInitialValue ); } } // ... } Need an additional pair of {}s for scoping lock When refactoring, take care that the if cannot be separated from the lock
  • 13. if and switch with initializer void safe_init () { if(std:: lock_guard <std::mutex > lk(mx_); v.empty ()) { v.push_back(kInitialValue ); } // ... } lk is scoped by the if.
  • 14. if and switch with initializer if(auto p = m.try_emplace(key , value ); !p.second) { FATAL("Element already registered"); } else { process(p.second ); } Avoids polluting the enclosing namespace with identifiers.
  • 15. Compiler support for if and switch with initializer Only gcc 7 and clang 3.9 support it already.
  • 16. Structured Bindings std::tie is not as useful as it should be: std::map <std::string , int > my_map; auto const ret = my_map.insert ({"key", 42}); std::map <std::string , int >:: iterator it; bool was_inserted; std::tie(it , was_inserted) = ret; We lose type deduction for the iterator type. We lose the const qualifier. Separate declaration often not feasible for non-trivial types.
  • 17. Structured Bindings - To the rescue! std::map <std::string , int > my_map; auto const [it , was_inserted] = my_map.insert ({"key", 42});
  • 18. Structured Bindings - Destructuring But wait, there’s more: struct Foo { int i; float f; std:: string s; }; Foo f; // ... auto [natural , real , text] = f;
  • 19. Structured Bindings Alright, cool. But how is this a major feature?
  • 20. Some preliminary boilerplate... struct any_type { template <class T> constexpr operator T(); // non explicit }; template <class T, class ... TArgs > class is_braces_constructible ; // std:: true_type if we can construct // a T from the TArgs
  • 21. Struct to tuple template <class T> auto to_tuple(T&& object) { using type = std:: decay_t <T>; if constexpr( is_braces_constructible <type , any_type , any_type >{}) { auto && [p1 , p2] = object; return std:: make_tuple(p1 , p2); } else if constexpr( is_braces_constructible <type , any_type >{}) { auto && [p1] = object; return std:: make_tuple(p1); } else { return std:: make_tuple (); } }
  • 22. Simple compile-time reflection Full example at https://www.reddit.com/r/cpp/comments/4yp7fv/c17_ structured_bindings_convert_struct_to_a_tuple/. Once we have tuples, we can do all kinds of metaprogramming (see Boost Hana) Not clear how much benefit structured bindings really bring, but chances are they will turn out more powerful than they seem at first glance.
  • 23. Structured bindings + if with initializer std::map <std::string , int > my_map; if(auto const [it , was_inserted] = my_map.insert ({"key", 42}); !was_inserted) { throw InsertionFailed (); }
  • 24. Compiler support for structured bindings Only (partially) supported in Clang 4.0 today.
  • 25. Concepts TS (not part of C++17) Specify constraints for template arguments. template <typename T> T const& min(T const& a, T const& b) { return (a < b) ? a : b; }
  • 26. Concepts Example template <typename T> concept bool LTComparable = requires(T a, T b) { { a < b } -> bool; }; template <LTComparable T> T const& min(T const& a, T const& b) { return (a < b) ? a : b; }
  • 27. Error messages with concepts Here’s what happens if we try to use min with a type Foo that does not have operator<: In function ’int main ()’: error: cannot call function ’const T& min(const T&, const T&) [with T = Foo]’ std :: cout << min(a, b) << std :: endl; ^ note: constraints not satisfied T const& min(T const& a, T const& b) ^~~ note: within ’template <class T> concept const bool LTComparable <T> [with T = Foo]’ concept bool LTComparable = requires(T a, T b) { ^~~~~~~~~~~~ note: with ’Foo a’ note: with ’Foo b’ note: the required expression ’(a < b)’ would be ill -formed
  • 28. Error messages with concepts Here’s what happens if there is an operator<, but it does not return bool: In function ’int main ()’: error: cannot call function ’const T& min(const T&, const T&) [with T = Foo]’ std :: cout << min(a, b) << std :: endl; ^ note: constraints not satisfied T const& min(T const& a, T const& b) ^~~ note: within ’template <class T> concept const bool LTComparable <T> [with T = Foo]’ concept bool LTComparable = requires(T a, T b) { ^~~~~~~~~~~~ note: with ’Foo a’ note: with ’Foo b’ note: ’operator <(a, b)’ is not implicitly convertible to ’bool ’
  • 29. Concepts Concepts are not checked for completeness. The implementation may use a concept parameter like any typename. template <LTComparable T> T const& max(T const& a, T const& b) { return (a > b) ? a : b; } Constraints can be used instead of SFINAE to remove functions from the overload set. template <typename T> requires std:: is_integral <T>:: value void ints_only(T i);
  • 30. Writing concepts Defining good concepts is non-trivial. Concepts are meant to represent fundamental concepts in an application domain (hence the name ”concepts”). Similarly throwing together a set of syntactic constraints to be used for a the arguments for a single class or algorithm is not what concepts were designed for and will not give the full benefits of the mechanism. From the C++ Core Guidelines 4 4 https://github.com/isocpp/CppCoreGuidelines/blob/master/ CppCoreGuidelines.md# t20-avoid-concepts-without-meaningful-semantics
  • 31. Writing concepts In the current TS, concepts only allow checking syntactical properties. However, concepts should only be designed from meaningful semantics (potentially including space/time complexity). Unfortunately, we cannot have non-trivial semantics without proofs. Concepts0x approximated proofs with axioms, in Concepts Lite they are gone completely.
  • 32. Writing concepts Do not be mislead by the current feature state concepts! Concepts are not about syntax. Always design your concepts on paper from clear, logical semantics. Then try to identify the parts that overlap with what the compiler can check. Take the compiler’s help where you can get it. Document the rest. Important is not how much support you get from the compiler, but how you think about your code.
  • 33. Thinking about concepts Alex Stepanov’s books 5 Take a look at functional programming 5 If you have only time for one, choose the one on the right
  • 34. Compiler support for concepts Currently only on gcc 6.1 with -fconcepts Stepanov-style concepts #if !defined __cpp_concepts || __cpp_concepts < 201507 # define LTComparable typename #endif template <LTComparable T> T const& min(T const& a, T const& b);
  • 36. Vocabulary Types - std::optional std:: optional <Value > readValue (); // ... auto const v = readValue (); if(v) { useValue (*v); } useValue(v.value_or(default_value ));
  • 37. Constructing std::optional auto empty = std:: optional <Value >(); auto also_empty = std:: optional(std:: nullopt ); auto def_constr = std:: make_optional <Value >(); auto value = std:: make_optional(v); auto from_args = std:: make_optional <Value >(arg1 , arg2 ); auto from_init_list = std:: make_optional <std::vector <int >> ({1 ,2 ,3 ,4 ,5});
  • 38. Compiler support for std::optional Supported in clang 4, gcc 7 and VC 15. Also: Boost.Optional in Boost 1.30 with slightly different interface.
  • 39. Vocabulary Types - std::variant std:: variant <int , float , std::string > v = 42; int n = std::get <int >(v); v = std:: string("Narf"); std:: string s = std::get <std::string >(v); float f = std::get <float >(v); // throws std:: bad_variant_access
  • 40. Polymorphism with variants struct Circle { float getArea () const; }; struct Square { float getArea () const; }; struct Triangle { float getArea () const; }; typedef variant <Circle , Square , Triangle > Shape; struct GetShapeAreaVisitor { template <typename T> float operator ()(T const& s) { return s.getArea (); } }; float getArea(Shape const& s) { return std:: visit( GetShapeAreaVisitor {}, s); }
  • 41. Variant details std::variant is almost-never-empty. A variant always holds an instance of one of its Ts. If a type-changing assignment throws, variant might have to revert to a special valueless state valueless by exception(). In the absence of exceptions, variants give the never-empty guarantee. Supported in gcc 7 and VC 15. Available with slightly different interface and semantics in Boost 1.31.
  • 42. Vocabulary Types - std::any std::any any_value; assert (! any_value.has_value ()); any_value = std:: make_any <std::string >("narf"); any_value = std:: make_any <int >(42); int i = std:: any_cast <int >( any_value ); auto* is_null = std:: any_cast <std::string >(& any_value ); std:: any_cast <std::string >( any_value ); // throws std:: bad_any_cast
  • 43. Details of std::any Prefer std::variant, if possible. Type-erasure in std::any requires heap allocation. Little better than a void*. Supported in gcc 7, clang 4 and VC 15. Available in Boost 1.23 with slightly different interface.
  • 44. Vocabulary Types - std::string view void processString(char const* str); // loses length void processString(std:: string const& str); // might make a copy void processString(char const* str , std:: size_t len); // yuck!
  • 45. Vocabulary Types - std::string view void processString(std:: string_view const& str);
  • 46. Details of std::string view A non-owning view on an immutable string. Implemented as a std::basic string view template, similar to std::string. Can be constructed from a std::string or a const pointer. When constructing from pointer, if no length is given, string must be null-terminated and length will be computed at construction. Constructing views on a substring requires no copy. Supported in gcc 7, clang 4 and VC 15. Available in the GSL (https://github.com/Microsoft/GSL)
  • 47. Ranges TS (not part of C++17) The STL achieves great things by separating algorithms from data structures through iterators. But iterators can be awkward to use. c.erase(remove_if(begin(c), end(c), pred), end(c)); Ranges consists of two parts: An STL-like library that is based on ranges instead of iterators. Works with the existing STL containers. Concepts for both the classic STL and the new ranges parts
  • 48. Sentinels Iterators point to elements. A range in STL is spanned by an iterator to the first element and an iterator to one-past-the-last. Except that end iterator might not really point to anything. If we are dealing with a range where not all elements are stored in memory, obtaining and end iterator might actually require iterating the whole range. Ranges introduces the notion of a sentinel. A sentinel can be compared to an iterator. Both are equal if the iterator points to the end element. A range in ranges is spanned by an iterator and a sentinel.
  • 49. What is a range? Something that you can call begin and end on. template <class T> using iterator_t = decltype(ranges :: begin(declval <T& >())); template <class T> using sentinel_t = decltype(ranges ::end(declval <T& >())); template <class T> concept bool Range () { return requires { typename sentinel_t <T>; }; };
  • 50. Ranges - Actions In-place mutation. Composable. action :: remove_if(c, pred ); Pipe syntax: vi = std:: move(vi) | action :: sort | action :: unique;
  • 51. Ranges - Views Non-mutating, lazy sequence manipulation. Composable. Cheap to create and copy. auto odd = []( int i){ return i % 2 == 1; }; auto to_str = []( int i){ return std:: to_string(i);} using namespace ranges; std::vector <int > vi = view :: ints (1 ,11); // vi = {1,2,3,4,5,6,7,8,9,10}; auto rng = vi | view :: remove_if(odd) | view :: transform(to_str ); // rng == {"2" ,"4" ,"6" ,"8" ,"10"};
  • 52. Ranges - Compiler support You can use ranges today! Reference implementation range-v36 works on gcc 4.8.5, clang 3.5.2; Microsoft offers a fork that works on VC 147 Full experience requires concepts language support by the compiler, but even without that it’s a pretty great library. Also: If you find bugs in the TS spec now, it is way easier to fix than once it goes IS. 6 https://github.com/ericniebler/range-v3 7 github.com/microsoft/Range-V3-VS2015
  • 53. Wrapping up... Lots of features are available for use already today, especially from the library. Small features can make a big difference in everyday work. Other features might be bigger than they seem at first. Don’t let lack of compiler support keep you from changing how you think about your code today.
  • 54. Thanks for your attention.