anthonycalandra / modern-cpp-features Goto Github PK
View Code? Open in Web Editor NEWA cheatsheet of modern C++ language and library features.
License: MIT License
A cheatsheet of modern C++ language and library features.
License: MIT License
example:
auto f = []<typename T>(std::vector<T> v) {
// ...
};
we use f<int>(v)
to call function. f
is a lambda function object.
if we want f
is a value returned from this lambda expression immediately call, how to do?
auto f = []<typename T>(std::vector<T> v) {
// ...
}<int>(v);
is this right? tried in online compiler but failed. What's the problem...
one of the two major features: concept & module , in c++20
The collection of c++ features is really good. While going through c++11.md, I found one wrong comment.
"int&& xr2 = 0; // xr2
is an lvalue of type int&&
-- binds to the rvalue temporary, 0
"
Here xr2 should be rvalue reference as there is no type deduction.
Kindly look into this.
auto {x, y, z} = expr;
should be auto [ x, y, z ] = expr;
.
noexcept
isn't mentioned anywhere at the moment.
Please refer to new feature modules added in C++20 which is not included here,
Title.
char8_t
is a fundamental type of C++20, not a library feature.char16_t
and char32_t
are fundamental types of C++11 (them also aren't library features).The ASM output will probably not be useful for beginners. It might be easier to think of the following example like having the expression square(2)
replaced with the value 4
at compile-time.
int a = square(2);
Additionally, mention that constexpr
doesn't imply that the expression is guaranteed to be evaluated at compile-time, rather, it makes it explicit that the compiler can do so.
const int x = 0;
auto x1 = x; // int
decltype(auto) x2 = x; // const int
int y = 0;
int& y1 = y;
auto y2 = y; // int
decltype(auto) y3 = y; // int& <--------------this should be decltype(auto) y3 = y1; right?
int&& z = 0;
auto z1 = std::move(z); // int
decltype(auto) z2 = std::move(z); // int&&
In the C++ 11 Language features, Function Trailing Return Types isn't in the list.
According to https://en.cppreference.com/w/cpp/language/functions, this is a feature in C++ 11, and helps with writing arguably more readable code.
Member functions like:
struct S {
void f1() &;
void f2() &&;
void f3() const &;
void f4() const &&;
};
are missing.
There are set of attributes coming with the latest C++ standard like [[nodiscard]], [[maybe_unused]], and [[fallthrough]].
Consider to add them into your beautiful docs.
With C++11/14, you have the ability to create std::shared_ptr<T>
and std::unique_ptr<T>
smart pointers with std::make_shared<T>
and std::make_unique<T>
respectively.
There are some important differences when creating these pointers using their constructors vs. make_XXX equivalents in the way they are allocated.
Might be worthwhile adding a blurb about on scenarios where one is preferred over the other and the gotchas involved. Subtle differences that most people won't pick-up on, but still important to be aware of.
__has_include
was introduced in C++17. Might be nice to include it (no pun intended):
https://en.cppreference.com/w/cpp/preprocessor/include
Great summary! Thanks! It would be even better if you would include references to WG21 papers (final version) describing that specific language or library feature. Symbolic references to the standard sections a la [stmt.if] would be great too.
Original example snap from std::span section
+++++++++++++++++++++++++++++++++
constexpr size_t LENGTH_ELEMENTS = 3;
int* arr = new int[LENGTH_ELEMENTS]; // arr = {0, 0, 0}
// Fixed-sized span which provides a view of arr
.
std::span<int, LENGTH_ELEMENTS> span = arr;
span[1] = 1; // arr = {0, 1, 0}
+++++++++++++++++++++++++++++++++
A small test in C++20 compatible compiler throws conversion type mismatch error
++++++++++++++++++++++++++++++++++
└─$ cat span_test.cpp
#include
#include
#include
int main()
{
constexpr size_t ARR_SIZE = 4;
int* arr = new int[ARR_SIZE];
std::span<int, ARR_SIZE> sp = arr;
}
┌──(suaich㉿Suva-Laptop)-[~/cpp/C++20/span]
└─$ g++ -std=c++2b span_test.cpp
span_test.cpp: In function ‘int main()’:
span_test.cpp:10:39: error: conversion from ‘int*’ to non-scalar type ‘std::span<int, 4>’ requested
10 | std::span<int, ARR_SIZE> sp = arr;
| ^~~
┌──(suaich㉿Suva-Laptop)-[~/cpp/C++20/span]
└─$
++++++++++++++++++++++++++++++++++
What would the definition of
my_integer_sequence
be?
https://github.com/AnthonyCalandra/modern-cpp-features/blob/master/CPP11.md#rvalue-references
auto&& al2 = x; // `al2` is an lvalue of type `int&`
Since x is an L-value, I had assumed it should cause a compiler error, just as the line above it did:
int&& xr = x; // compiler error -- `x` is an lvalue
But it seems that the compiler silently consumes the extra & if it is auto!?
I had to log onto freenode chat and ask someone about this, because it appeared to be an error in the tutorial. They explained to me that this is a separate concept known as a Universal Reference.
https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers
You should at least make mention of the concept at that point so that it becomes clear what is happening. Even better, with hyperlink to detailed explanation.
You have written about benchmarking code and gave an example with std::chrono::system_clock. However cppreference.com suggests std::chrono::steady_clock for the purpose of benchmarking with the following explanation (http://en.cppreference.com/w/cpp/chrono/steady_clock):
Class std::chrono::steady_clock represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward. This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.
Write a program that will display the following output.
Need some help.!!
SEE: Title.
Include an example of inline static members in the "Inline variables" section.
You can add std::sample which is C++17 feature.
e1 op1 ... op2 e2
According to http://en.cppreference.com/w/cpp/language/fold, op1 and op2 should be the same. Is this a typo or a new feature?
README.md says that:
int random = get_random_number_between_x_and_y(0, 3);
[[likely]] if (random > 0) {
// body of if statement
// ...
}
[[unlikely]] while (unlikely_truthy_condition) {
// body of while statement
// ...
}
This Working Draft, Standard for ProgrammingLanguage C++ (published on 2021-03-17) gives a similar example, but [[unlikely]] appears after the right parenthesis, as opposed to the example given in README.md.
if (n > 5) [[unlikely]] { // n > 5is considered to be arbitrarily unlikely
g(0);
return n * 2 + 1;
}
Also, cppreference gives a similar example where [[likely]] appears after the right parenthesis:
constexpr double pow(double x, long long n) noexcept {
if (n > 0) [[likely]]
return x * pow(x, n - 1);
else [[unlikely]]
return 1;
}
Regardless of the position of the likely and unlikely attributes, the code will compile. I wonder if there's a difference? If not, should we update the example in README.md?
Thanks!
C++11 also introduced atomic and thread, but cannot be seen here.
Is C++20 section missing __VA_OPT language attribute for better support of variadic macros? e.g., some detailed usage outlined here
https://www.scs.stanford.edu/~dm/blog/va-opt.html
Is there any particular reason why the examples on type traits compare the value of the trait to 1?
static_assert(std::is_integral<int>::value == 1);
I'd suggest to either drop the comparison or to compare to true
in all examples.
The doc is great! Hoewever some areas are still missing.
C++11 intoduced raw string literals: https://en.cppreference.com/w/cpp/language/string_literal
It is useful in many different areas, like strings with quotes, multiline strings and for example windows paths without escaping backslashes:
const char win_path[] = R"(c:\some\unescaped\path)";
The same cppreference link also mentions u8/u16/u32 literals, but I'm not sure that their addition is major enough to include in a high-level list.
Great work 👍
However, in the list of C++ 11 features i am missing explicit conversion functions, s.a. http://en.cppreference.com/w/cpp/language/explicit
Add a link to decltype
in the decltype(auto)
section and vice-versa.
It would be great to have a brief information about modules, coroutines, and maybe three-way comparison operator.
Another suggestion would be to split the file into different .md files, such as CPP_11.md, 'CPP_14.md, andCPP_17.md`.
This way it would be a lot easier to follow each standard to study it separately without following a top to bottom concept that is a bit overwhelming in my humble opinion.
I find it confusing to start reading about the latest C++17 first and then have to scroll all the way down to the bottom to read about C++11 new features that I am more interested in.
Basically the README.md should played the role of the table of contents that lead the user to a different .md file that is fully dedicated to each C++ new-features release.
What do you think?
Suggestion by @stefanos82.
Hi,
First of all, great work, thank you so much!
Second: any plans to maintain this for c++20 or future releases?
thanks
Chris
I think in the section:
https://github.com/AnthonyCalandra/modern-cpp-features/blob/master/CPP11.md#forwarding-references
...the following is incorrect:
int&& z = 0;
f(z); // deduces as f(int&& &&) => f(int&&)
Only actual rvalues (temps) seem to deduce to && in a template. Not lvalues which reference rvalues.
According to using __PRETTY_FUNCTION__ inside the template, this looks like it should be:
int&& z = 0;
f(z); // deduces as f(int& &&) => f(int&)
TODO: Fix this error and add a case when using std::move
for clarity. Also, the CPP11 and README files are inconsistent.
Bug submitted by Kevin L.
Hi @AnthonyCalandra
Would you mind if I add an entry for semaphores:
https://en.cppreference.com/w/cpp/thread/counting_semaphore
?
In the section about tuples, the comment in the sample assumes that a literal string is detected as std::string
for the template parameter. This isn't accurate, it's const char*
.
If someone isn't sure about it, taking the code to compiler explorer, the output mentions (in a comment): std::tuple<int, char const*, char const*>
The comment should be changed by replacing the 2 std::string
occurrences to const char*
(or char const*
) or the sample should be changed to construct an std::string
from the string literal (either by passing it to a c-tor or by using C++14 UDLs).
If you want a PR, I'll be happy to create one, just let me know which of the options I suggested you prefer.
C++11 feature std::async is missing.
Possibly after this section: https://github.com/AnthonyCalandra/modern-cpp-features#constexpr-lambda
syntax:
auto l = [*this]{ some_member_fn(); };
Hi.
fallthrough example in the section is misleading.
Look at the explanation in the link:
May only be applied to a null statement to create a fallthrough statement ([[fallthrough]];).
A fallthrough statement may only be used in a switch statement, where the next statement to be executed is a statement with a case or default label for that switch statement.
The example is not compilable in its current state.
There is constexpr, consteval but constinit is not described.
It could be worth to add it.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.