-
Notifications
You must be signed in to change notification settings - Fork 44
grammar and other edits #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 11 commits
1ab37dc
61b1d33
dad108d
77a892d
a180d5b
3283d2b
e1d568a
18e998d
e0a43d1
42e9987
9899681
100c617
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,6 +24,7 @@ int main(){ | |
| } | ||
| ``` | ||
| ```c++ | ||
| // five | ||
| #include <iostream> | ||
|
|
||
| int sum(int a, int b); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -296,13 +296,26 @@ int main() { | |
|
|
||
| Немного best practices о том, как надо делать `swap`: | ||
| ```c++ | ||
| namespace my_lib { | ||
| struct big_integer {}; | ||
| void swap(big_integer&, big_integer&) {// ... //} | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. таких комментариев в языке нет, лучше
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
| } | ||
|
|
||
| template <class T> | ||
| void foo(T a, T b) { | ||
| // ... | ||
| using std::swap; | ||
| swap(a, b); | ||
| // ... | ||
| } | ||
|
|
||
| int main() { | ||
| my_lib::big_integer a1, b1; | ||
| foo(a1, b1); // выбирается my_lib::swap | ||
|
|
||
| int a2, b2; | ||
| foo(a2, b2); // выбирается std::swap | ||
| } | ||
| ``` | ||
| Теперь у нас получается шаблонный `std::swap` и, возможно, есть не-шаблонный ADL. | ||
| - Если есть ADL, выбирается он, потому что из шаблонного и не-шаблонного выбирается второй. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -271,3 +271,45 @@ void write(T0 const& arg0, Ts const& ...args) { | |
| write(args...); | ||
| } | ||
| ``` | ||
|
|
||
| ## Fold Expressions | ||
|
|
||
| В **C++17** появилась фича **Fold Expressions**, позволяющая сделать свёртку по элементам пака относительно бинарного оператора. | ||
|
|
||
| Мотивирующий пример: попробуем научиться проверять, есть ли тип (T) в паке. Так как пак в C++ имеет вид lazy array (То есть мы имеем право получить только Head и Tail), очевидна следующая реализация: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. имена типов и других идентификаторов лучше заключать в
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. часть предложения в скобках не должна начинаться с большой буквы
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. вроде fixed
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не знаю, является ли "C++26", но если является напишите
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "lazy array" это какой-то распространённый в таком контексте термин? я впервые слышу давай или ссылку, где он применяется, либо не будем его упоминать
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ну здесь имеется в виду lazy sequence, но я лучше это просто уберу
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перед сложным примером, уходящим в сторону метапрограммирования, полезно показать какой-нибудь более простой и типичный пример свёртки
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Добавил пример с sum |
||
|
|
||
| ```c++ | ||
| template <typename Type, typename... Pack> | ||
| struct have_type; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. может,
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
|
|
||
| template <typename Type, typename Head, typename... Tail> | ||
| struct have_type<Type, Head, Tail...> { | ||
| static constexpr bool value = std::is_same_v<Type, Head> || | ||
| have_type<Type, Tail...>::value; | ||
| // ^^^^^^^^^^^^^^^^^^^^^^^^ инстанс нового шаблона | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. комментарий стоит индентировать
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это не инстанс нового шаблона, это инстанцирование новой специализации всё того же шаблона
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. я не очень понимаю, что значит идентировать, но со "специализацией" согласен |
||
| }; | ||
|
|
||
| template <typename Type, typename Head> | ||
| struct have_type<Type, Head> { | ||
| static constexpr bool value = std::is_same_v<Type, Head>; | ||
| }; | ||
| ``` | ||
|
|
||
| Чем плоха такая реализация? Предположим в паке N элементов, тогда компилятор будет проводить N инстансов шаблона `have_type`. Как можно это пофиксить? Вспомним, что `...` ставится там, где перечисляются элементы. В Fold expressions это и используется. Тогда предыдущий пример можно переписать так: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ditto про идентификаторы
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
|
|
||
| ```c++ | ||
| template <typename Type, typename... Pack> | ||
| struct have_type; | ||
|
|
||
| template <typename Type, typename... Types> | ||
| struct have_type<Type, Types...> { | ||
| static constexpr bool value = std::is_same_v<Type, Types> || ...; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это не скомпилируется по нескольким причинам
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
| }; | ||
| ``` | ||
|
|
||
| Чем это хорошо? | ||
| - Нет рекурсии. | ||
| - Быстрее compile time, потому что меньше инстансов и у компилятора есть возможность делать оптимизации. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. английский ну совсем на ровном месте, давай заменим на "время компиляции"
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не совсем понял, о каких оптимизациях речь
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я здесь немного ошибся с примером в метапрограммировании (хотя здесь тоже должны быть оптимизации, потому что проиходит свёртка булов). Здесь всё-таки имеются в виду вообще оптимизации fold-ов, даже вне метапроги. Насчёт оптимизаций: я вообще думал, что компилятор умеет делать что-то типо свёртки констант в компайл тайме (Например свернуть sum(1, 2, 3, 4) в return 10), но почему-то когда я начал это на godbolt писать, то оно не воспроизвелось. Есть оптимизация булов https://godbolt.org/z/nbKcof5qf вот тут видно, что компилятор может соптимизировать вывод false после первого встреченного false, конечно он делает нечто подобное и в случае когда вызывается функция two, но он её не инлайнит, поэтому может быть больше джампов по программе например. Да и пример может быть сложнее. +у компилятора есть пространство для векторизации(то есть, допустим сложить несколько чиселок за 1 инструкцию). В общем случае, всё, что сказано выше заключено во фразе "Нет рекурсии", но я считаю важным написать про оптимизации
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я засомневался, что пример с оптимизацией булов действительно подходит, поэтому вот пример когда работает constant folding с делением https://godbolt.org/z/MYqYcnzG6 (с -O2) |
||
| - Легче читается и меньше кода. | ||
|
|
||
| Подробнее про Fold expressions на [cppreference](https://en.cppreference.com/w/cpp/language/fold.html). | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
five.cpp, тогда ужThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed