Standard C++ (Twitter)
C++20: Extend std::format for User-Defined Types--Rainer Grimm bit.ly/3lQTlXn #cpp
C++20: Extend std::format for User-Defined Types--Rainer Grimm bit.ly/3lQTlXn #cpp
Standard C++ (Twitter)
A brief introduction to C++ structured binding--Raymond Chen bit.ly/3k48u76 #cpp
A brief introduction to C++ structured binding--Raymond Chen bit.ly/3k48u76 #cpp
C++ (Rss)
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
C++ (Rss)
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
C++ (Rss)
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
A brief introduction to C++ structured binding
submitted by /u/vormestrand
[link] [comments]
Arthur O’Dwyer (Rss)
A case study in implementation inheritance
The more I deal with classically polymorphic code, the more I appreciate the
“modern” idioms that have grown up around it — the Non-Virtual Interface Idiom;
Liskov substitutability;
Scott Meyers’ dictum that classes should be either abstract or final; the
rule that every hierarchy should have exactly two levels; and the rule that
base classes express commonality of interface,
not reuse of implementation.
Today I’d like to present a chunk of code that shows how “implementation inheritance”
ended up causing trouble, and the particular patterns I applied to disentangle it.
Unfortunately, the offending code is pretty messy, so I’ll use a simplified and
domain-shifted example; and I’ll try to build it up in stages.
Step 1: Transactions
Let our domain be “banking transactions.” We have a classically polymorphic inheritance hierarchy,
because of course we do.
All kinds of transaction have certain APIs in common, and then each type also has its own
idiosyncratic APIs.
Step 2: Transaction filters
What our software is actually doing, though, isn’t executing transactions; it’s monitoring them
so that it can flag suspicious transactions. The software’s human operator can set up filters to
match against certain criteria, like “flag all transactions larger than $10,000” or “flag all
transactions where the person’s name is on watchlist W.” Internally, we represent the various
operator-configured filter types as a classically polymorphic hierarchy, because of course we do.
All filters have exactly the same public API.
Here’s an example of a simple filter:
Step 3: The first misstep
It turns out that some filters really want to access those idiosyncratic transaction-specific
APIs I mentioned earlier. Let’s say that
any transaction where the name of the customer who made the transaction was different from the
name on the account. For the sake of this example, our bank strictly enforces that
only the account holder is ever allowed to withdraw money from their account. So
only
transaction.
A case study in implementation inheritance
The more I deal with classically polymorphic code, the more I appreciate the
“modern” idioms that have grown up around it — the Non-Virtual Interface Idiom;
Liskov substitutability;
Scott Meyers’ dictum that classes should be either abstract or final; the
rule that every hierarchy should have exactly two levels; and the rule that
base classes express commonality of interface,
not reuse of implementation.
Today I’d like to present a chunk of code that shows how “implementation inheritance”
ended up causing trouble, and the particular patterns I applied to disentangle it.
Unfortunately, the offending code is pretty messy, so I’ll use a simplified and
domain-shifted example; and I’ll try to build it up in stages.
Step 1: Transactions
Let our domain be “banking transactions.” We have a classically polymorphic inheritance hierarchy,
because of course we do.
class Txn { ... };
class DepositTxn : public Txn { ... };
class WithdrawalTxn : public Txn { ... };
class TransferTxn : public Txn { ... };
All kinds of transaction have certain APIs in common, and then each type also has its own
idiosyncratic APIs.
class Txn {
public:
AccountNumber account() const;
std::string name_on_account() const;
Money amount() const;
private:
// virtual stuff
};
class DepositTxn : public Txn {
public:
std::string name_of_customer() const;
};
class TransferTxn : public Txn {
public:
AccountNumber source_account() const;
};
Step 2: Transaction filters
What our software is actually doing, though, isn’t executing transactions; it’s monitoring them
so that it can flag suspicious transactions. The software’s human operator can set up filters to
match against certain criteria, like “flag all transactions larger than $10,000” or “flag all
transactions where the person’s name is on watchlist W.” Internally, we represent the various
operator-configured filter types as a classically polymorphic hierarchy, because of course we do.
class Filter { ... };
class AmountGtFilter : public Filter { ... };
class NameWatchlistFilter : public Filter { ... };
class AccountWatchlistFilter : public Filter { ... };
class DifferentCustomerFilter : public Filter { ... };
class AndFilter : public Filter { ... };
class OrFilter : public Filter { ... };
All filters have exactly the same public API.
class Filter {
public:
bool matches(const Txn& txn) const {
return do_matches(txn);
}
private:
virtual bool do_matches(const Txn&) const = 0;
};
Here’s an example of a simple filter:
class AmountGtFilter : public Filter {
public:
explicit AmountGtFilter(Money x) : amount_(x) { }
private:
bool do_matches(const Txn& txn) const override {
return txn.amount() > amount_;
}
Money amount_;
};
Step 3: The first misstep
It turns out that some filters really want to access those idiosyncratic transaction-specific
APIs I mentioned earlier. Let’s say that
DifferentCustomerFilter wants to flagany transaction where the name of the customer who made the transaction was different from the
name on the account. For the sake of this example, our bank strictly enforces that
only the account holder is ever allowed to withdraw money from their account. So
only
class DepositTxn even bothers to record the name of the customer who made thetransaction.
class DifferentCustomerFilter : public Filter {
bool do_matches(const Txn& txn) const override {
if (auto *dtxn = dynamic_cast(&txn)) {
return dtxn->name_of_customer() != dtxn->name_on_account();
}C++ (Rss)
Compile and run desktop C++ apps in github codespaces
submitted by /u/Vadi2
[link] [comments]
Compile and run desktop C++ apps in github codespaces
submitted by /u/Vadi2
[link] [comments]
C++ – Типизированный язык программирования (Rss)
Оптимизация C++: совмещаем скорость и высокий уровень. Доклад Яндекса
Что влияет на скорость работы программ на C++ и как её добиться при высоком уровне кода? Ведущий разработчик библиотеки CatBoost Евгений Петров ответил на эти вопросы на примерах и иллюстрациях из опыта работы над CatBoost для x86_64.
Видео доклада
— Всем привет. Я занимаюсь оптимизацией для CPU библиотеки машинного обучения CatBoost. Основная часть нашей библиотеки написана на C++. Сегодня расскажу, какими простыми способами мы добиваемся скорости.
Читать дальше →
Оптимизация C++: совмещаем скорость и высокий уровень. Доклад Яндекса
Что влияет на скорость работы программ на C++ и как её добиться при высоком уровне кода? Ведущий разработчик библиотеки CatBoost Евгений Петров ответил на эти вопросы на примерах и иллюстрациях из опыта работы над CatBoost для x86_64.
Видео доклада
— Всем привет. Я занимаюсь оптимизацией для CPU библиотеки машинного обучения CatBoost. Основная часть нашей библиотеки написана на C++. Сегодня расскажу, какими простыми способами мы добиваемся скорости.
Читать дальше →
C++ – Типизированный язык программирования (Rss)
C++ Russia: что будем обсуждать уже через месяц
Всем привет!
До C++ Russia осталось меньше месяца — самое время показать вам, о чём там расскажут-то.
Как обычно, спектр тем будет широкий — от прикладных («решаем нетривиальные задачи средствами современного CMake») до довольно академических («как лямбды в C++ и других языках соотносятся с исходной идеей лямбд»). Как обычно, состав спикеров интересный, и о некоторых технологиях поведают их непосредственные авторы: обсудим Compiler Explorer с Мэттом Годболтом, а про GWP-ASan расскажет Константин Серебряный.
А подробнее о блоках программы и каждом докладе — под катом. Читать дальше →
C++ Russia: что будем обсуждать уже через месяц
Всем привет!
До C++ Russia осталось меньше месяца — самое время показать вам, о чём там расскажут-то.
Как обычно, спектр тем будет широкий — от прикладных («решаем нетривиальные задачи средствами современного CMake») до довольно академических («как лямбды в C++ и других языках соотносятся с исходной идеей лямбд»). Как обычно, состав спикеров интересный, и о некоторых технологиях поведают их непосредственные авторы: обсудим Compiler Explorer с Мэттом Годболтом, а про GWP-ASan расскажет Константин Серебряный.
А подробнее о блоках программы и каждом докладе — под катом. Читать дальше →
C++ – Типизированный язык программирования (Rss)
Цифровой рентген: прогулка по Эльбрусу
Привет Хабр!
В прошлый раз писал про проект по рентгеновской инспекции печатных плат. Сейчас мы сильно продвинулись, есть рабочий прототип софта плюс “потыкали палочкой” в Эльбрус. Про этот опыт я и хочу рассказать.
Интро
На старте проекта нам удалось найти дополнительное финансирование, основным условием была работа ПО полная кроссплатформенность, в том числе поддержка отечественных процессоров. На тот момент наиболее производительным вариантом для десктоп машин был Эльбрус 8С (пока он им и остается, 8СВ еще вроде не вышел). Мы купили две станции «Эльбрус 801-РС» напрямую от МЦСТ. Сейчас их стоимость указана на сайте, год назад были чуть дороже.
Из курьезных мелочей, с которыми столкнулись при закупке – бумажные заявки на поставку. Сразу советую заключить договор NDA, это даст доступ к свежим инструментам разработчика (оформление около месяца). Приехали машины быстро, по комплектации – есть проблема с кастомизацией на стороне МЦСТ. Проще докупить и поставить самим нужные видеокарты или периферию. Перечень проверенного оборудования/чипов карт пока есть только в багтрекере МЦСТ, хотя стоило бы опубликовать список на вики ресурсе по Эльбрусам. Читать дальше →
Цифровой рентген: прогулка по Эльбрусу
Привет Хабр!
В прошлый раз писал про проект по рентгеновской инспекции печатных плат. Сейчас мы сильно продвинулись, есть рабочий прототип софта плюс “потыкали палочкой” в Эльбрус. Про этот опыт я и хочу рассказать.
Интро
На старте проекта нам удалось найти дополнительное финансирование, основным условием была работа ПО полная кроссплатформенность, в том числе поддержка отечественных процессоров. На тот момент наиболее производительным вариантом для десктоп машин был Эльбрус 8С (пока он им и остается, 8СВ еще вроде не вышел). Мы купили две станции «Эльбрус 801-РС» напрямую от МЦСТ. Сейчас их стоимость указана на сайте, год назад были чуть дороже.
Из курьезных мелочей, с которыми столкнулись при закупке – бумажные заявки на поставку. Сразу советую заключить договор NDA, это даст доступ к свежим инструментам разработчика (оформление около месяца). Приехали машины быстро, по комплектации – есть проблема с кастомизацией на стороне МЦСТ. Проще докупить и поставить самим нужные видеокарты или периферию. Перечень проверенного оборудования/чипов карт пока есть только в багтрекере МЦСТ, хотя стоило бы опубликовать список на вики ресурсе по Эльбрусам. Читать дальше →
CppCon (Youtube)
Build Everything From Scratch : A Case Study in Fear - Dave Steffen - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
Two years ago Titus Winters gave a talk at Pacific++ called "C++ Past vs. Future" where he described the perils of linking files compiled at different times in different ways, which can easily lead to One-Definition-Rule violations and undefined behavior. This is not an abstract or theoretical problem, nor one restricted to C++, but is a present menace waiting in our build systems and in our operating system's prebuilt libraries. As a public service, I present a case study of a compiler upgrade, a deeply mysterious bug, and a popular open-source project with a C interface that cannot be delivered as a pre-built library without putting users in peril.
---
Dave Steffen completed his Ph.D. in theoretical physics at C...
Read full post
Build Everything From Scratch : A Case Study in Fear - Dave Steffen - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
Two years ago Titus Winters gave a talk at Pacific++ called "C++ Past vs. Future" where he described the perils of linking files compiled at different times in different ways, which can easily lead to One-Definition-Rule violations and undefined behavior. This is not an abstract or theoretical problem, nor one restricted to C++, but is a present menace waiting in our build systems and in our operating system's prebuilt libraries. As a public service, I present a case study of a compiler upgrade, a deeply mysterious bug, and a popular open-source project with a C interface that cannot be delivered as a pre-built library without putting users in peril.
---
Dave Steffen completed his Ph.D. in theoretical physics at C...
Read full post
CppCon (Youtube)
Where is my object? - Staffan Tjernström - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
Looking outside-in from a user perspective at the ongoing saga of making objects appear in C++ from out-of-process (file mappings, message queues, device drivers, etc).
---
Staffan has been busting latency issues since the mid-80's. These days he's a C++ subject expert at Susquehanna International Group, where he spends his days working in an MSVC environment using Powershell and emacs.
---
Streamed & Edited by Digital Medium Ltd - events.digital-medium.co.uk
[email protected]
Where is my object? - Staffan Tjernström - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
Looking outside-in from a user perspective at the ongoing saga of making objects appear in C++ from out-of-process (file mappings, message queues, device drivers, etc).
---
Staffan has been busting latency issues since the mid-80's. These days he's a C++ subject expert at Susquehanna International Group, where he spends his days working in an MSVC environment using Powershell and emacs.
---
Streamed & Edited by Digital Medium Ltd - events.digital-medium.co.uk
[email protected]
CppCon (Youtube)
Become A Game Developer In 5 Minutes Or Less - Mathieu Ropert - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
A 5 minute crash course in game development aimed at lifting up the veil of mystique that surrounds the industry
---
French C++ expert working on (somewhat) historical video games. Decided to upgrade his compiler once and has been blogging about build systems ever since. Past speaker at CppCon, Meeting C++ and ACCU. Used to run the Paris C++ User Group. Currently lives in Sweden.
---
Streamed & Edited by Digital Medium Ltd - events.digital-medium.co.uk
[email protected]
Become A Game Developer In 5 Minutes Or Less - Mathieu Ropert - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
A 5 minute crash course in game development aimed at lifting up the veil of mystique that surrounds the industry
---
French C++ expert working on (somewhat) historical video games. Decided to upgrade his compiler once and has been blogging about build systems ever since. Past speaker at CppCon, Meeting C++ and ACCU. Used to run the Paris C++ User Group. Currently lives in Sweden.
---
Streamed & Edited by Digital Medium Ltd - events.digital-medium.co.uk
[email protected]
CppCon (Youtube)
Code Samples That Compile Even More Easily - Clare Macrae - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
I’ve previously shown how to embed snippets from Tests and other compiled code in to Markdown docs, so the docs are always right, and users can trust your docs - using a tool called mdsnippets.
This year, it's even easier to keep code in your Markdown docs automatically uptodate.
---
Clare has worked in software development for over 30 years, and in C++ for 20 years.
Since 2017, she has used her spare time to work remotely with Llewellyn Falco on [ApprovalTests.cpp](https://github.com/approvals/ApprovalTests.cpp), to radically simplify testing of legacy code. She has enjoyed this so much that she recently went independent, to focus even more on helper others work more easily with legacy code.
Clare was until recently a P...
Read full post
Code Samples That Compile Even More Easily - Clare Macrae - CppCon 2020
https://cppcon.org/
https://github.com/CppCon/CppCon2020
---
I’ve previously shown how to embed snippets from Tests and other compiled code in to Markdown docs, so the docs are always right, and users can trust your docs - using a tool called mdsnippets.
This year, it's even easier to keep code in your Markdown docs automatically uptodate.
---
Clare has worked in software development for over 30 years, and in C++ for 20 years.
Since 2017, she has used her spare time to work remotely with Llewellyn Falco on [ApprovalTests.cpp](https://github.com/approvals/ApprovalTests.cpp), to radically simplify testing of legacy code. She has enjoyed this so much that she recently went independent, to focus even more on helper others work more easily with legacy code.
Clare was until recently a P...
Read full post