🍌 C++ Feed
306 subscribers
218 photos
12.7K links
Агрегатор всего подряд про C++.

Для связи: @smertig

Powered by https://github.com/Smertig/banana
Download Telegram
C++
Bjarne Stroustrup on "dead bodies of type theorists"

I can't produce a link off the top of my head, but I remember Bjarne Stroustrup saying (on a few occasions, in a talk or a panel) that "non-type template parameters were introduced in C++ over the dead bodies of some type theorists" (quote from memory). This surprises me since types depending on values is a fundamental concept in Martin-Löf type theory which is older than C++. Does anyone have any knowledge on what feedback Bjarne Stroustrup received from type theorists? submitted by /u/dylanzdavies
[link] [comments]
C++ – Типизированный язык программирования
[Из песочницы] Кривые Безье. Немного о пересечениях и как можно проще

Article

Вы сталкивались когда-нибудь с построением (непрерывного) пути обхода кривой на плоскости, заданной отрезками и кривыми Безье?

Вроде бы не сильно сложная задача: состыковать отрезки кривых в один путь и обойти его "не отрывая пера". Замкнутая кривая обходится в одном направлении, ответвления — в прямом и обратном, начало и конец в одном узле.

Всё было хорошо, пока из-под рук дизайнеров не стали вылезать монструозные пути, где отдельные кривые могли пересекаться или не точно состыковываться. Объяснение было предельно простым — визуально они все лежат как надо, а для станка, который этот путь будет обходить, такие отклонения незаметны.

Вооружившись знанием о величине максимально допустимого отклонения, я приступил к исследованию, результатами которого хочу поделиться. Читать дальше →
Arthur O’Dwyer
A very short war story on too much overloading

On my previous post
“Inheritance is for sharing an interface (and so is overloading)” (2020-10-09),
a couple of Reddit commenters expressed disbelief at my third section, where I claimed that the
vector::erase overload set was poorly designed. They had never run into the common bug

// Oops!
v.erase(
std::remove_if(v.begin(), v.end(), isOdd)
);


For more on erasing from STL containers, see “How to erase from an STL container” (2020-07-08).

Here’s another example of grief caused by overuse-of-overloading, which I just ran into at work last week.

class mgr_t : public asio_actor {
~~~
virtual std::string getname() const = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio, const std::string type,
bool enrich = false) = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio, selector f, unsigned &id,
bool enrich = false) = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio,
bool enrich = false) = 0;
virtual void subscribe_connect(actor::ptr tgt, connhandler handler,
priority::level prio) = 0;
virtual void subscribe_disconnect(actor::ptr tgt, connhandler handler,
priority::level prio) = 0;
~~~
};


And then there’s a caller in some other repository that does this:

this->message_ = std::string("subscription failed");
return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, std::string("queue-stats"));


You might look at those lines and think: Ah, the casts to std::string are redundant. This is just
a Java programmer’s attempt to keep track of where “string objects” are created. I can remove them.

You’d be right about the first cast, but it turns out you’d be wrong about the second!

return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, std::string("queue-stats"));


is a call to mgr_t::subscribe(actor::ptr, msghandler, priority::level, const std::string, bool = false). But

return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, "queue-stats");


is a call to mgr_t::subscribe(actor::ptr, msghandler, priority::level, bool = false)!
Because "queue-stats", after decaying to const char*, would rather implicitly convert
to the built-in type bool than to the user-defined type std::string. (Godbolt.)

The above snippet exemplifies many sins which I’ve previously discussed on this blog. See:



“Default function arguments are the devil” (2020-04-18)


const is a contract” (2019-01-03) re the missing ampersand


“PSA: shared_ptr() is not make_shared()” (2019-03-06) re actor::ptr


And of course it should be using the Non-Virtual Interface idiom, but I haven’t got a blog post
dedicated to that subject, yet. See
“CppCon 2019 talks are up” (2019-10-18).



Nevertheless, I think the primary sin here — or at least the “first among equals
— is that it has three overloads of subscribe, doing radically different things with (s
C++
CppCon 2020 presentation recommendations?

I've seen four videos so far and I can only recommend one of them as being interesting and/or well presented: The Many Shades of reference_wrapper - Zhihao Yuan - CppCon 2020 Do you guys have recommendations? submitted by /u/lookatmetype
[link] [comments]
C++
Awkward passing of Allocators and Schedulers to C++20 Coroutines

C++20 coroutines are here and give us some really intersting functionality. When working on library code I've encountered inelegance in the following: PMR allocators to a coroutine not practical because you cannot access arguments provided to coroutines. Seems like get_return_object could be provided with the function arguments, anybody see problems with that? Passing ordinary allocators to coroutines constructable just like containers: ​ constexpr vector( size_type count, const T& value, const Allocator& alloc = Allocator()); Passing various worker queues to different coroutines without singleton or global data. I'm interested in making a proposal to resolve some of my concerns with coroutines.Getting opinions from the community is really important to me. Finding out I'm wrong about a problem is even more important... Hope people don't mind a few of these related posts. Are others finding the same issue as me?Is this something people want? I'll keep adding to this list: Idea 1: Provide function arguments to get_return_object Pros: Could grab an allocator/queue/whatever from here. Could use this for logging and instrumentation. Could just be an additional overload avaliable for get_return_object. Cons: Provided arguments could be mutated, this might lead to confusing situations. submitted by /u/Seppeon
[link] [comments]
Modernes C++ - ModernesCpp.com
C++20: Extend std::format for User-Defined Types

Peter Gottschling presented in his last post "std::format in C++20" the basics to the new formatting library in C++20. In today's post Peter writes about the formatting of user-defined types.
Bartek's coding blog
Increased Complexity of C++20 Range Algorithms Declarations - Is It Worth?

With the addition of Ranges and Concepts in C++20, our good old algorithm interfaces got super long “rangified” versions. For example, copy is now 4 lines long… and it’s just the declaration! template std::weakly_incrementable O>
requires std::indirectly_copyable, O>
constexpr ranges::copy_result, O>
copy(R&& r, O result);
How to decipher such a long declaration? What benefits do we get instead? Is it worth it? Let’s find out. Read more...
C++
std::i/ostream's are a bit too oversized for both usage and implementation. Are there lighter alternatives widely used?

Disclaimer: I'm not solving any specific production case. Standard input/output stream specifications include a lot of details - locales, buffering, large set of virtual functions. And they're known for their performance implications. So I was wondering if there's some simpler version of i/o interface, coming from some 3rd party library, which is widely used. Something like this: struct reader { virtual std::size_t read(std::span buffer) = 0; } struct writer { virtual std::size_t write(std::span buffer) = 0; virtual void flush() = 0; } Or does everyone either just use std::i/o stream's or reimplements concept above from scratch? submitted by /u/target-san
[link] [comments]
C++
bitflags v1.3.0 - raw flags support

Hi everybody, New version of bitflags library is released these days! Previously, you could create your flags only by writing something like: BEGIN_BITFLAGS(Flags) FLAG(none) FLAG(flag_a) FLAG(flag_b) FLAG(flag_c) END_BITFLAGS(Flags) Each flag is consisted of raw value (bits) and flag's name. So you could get a string representation of each flag by writing: Flags::flag_a.name . In the new version, you can create raw flags, i.e. flags without string representation. Purpose of this feature is to provide light version that would take up as little space as possible: BEGIN_RAW_BITFLAGS(RawFlags) RAW_FLAG(none) RAW_FLAG(flag_a) RAW_FLAG(flag_b) END_RAW_BITFLAGS(RawFlags) What do you think of this feature? What's next? In the next version, support for C++11 and C++14 will be added. Thank you all! submitted by /u/mNutCracker
[link] [comments]
C++
Modern C++ Undo/Redo framework

Hello everyone, just sharing my latest development.
https://github.com/ryder052/History Happy coding :) submitted by /u/Ryder052
[link] [comments]
C++
When a coroutine ‘suspends’, does control flow halt or pass to the caller?

https://github.com/lewissbaker/cppcoro/blob/master/lib/async_manual_reset_event.cpp I’m trying to understand what happens when await_suspend returns true. Does the thread of execution pass control back to where co_await was called by the user? Or does the thread of execution simply halt until we get a call to resume? Put another way, after await_suspend returns true, where does the EIP register point? Are CPU resources returned to the OS? After iterating through the linked list on a call to set(), how does resume() know which threads of execution to resume on? Does the coroutine handle hold this information? submitted by /u/XiPingTing
[link] [comments]
Standard C++ (Twitter)

Upsetting Opinions about Static Analyzers bit.ly/3iRQueX #cpp
C++ – Типизированный язык программирования
Обидно за мнения про статические анализаторы кода

Инструменты статического анализа кода ушли далеко вперёд. Это вовсе не те "линтеры", которые активно применялись 20 лет тому назад. Однако многие по-прежнему относятся к ним, как к очень простым инструментам. Обидно. Обидно, как за методологию анализа кода в целом, так и за инструмент PVS-Studio.


Читать дальше →
Jason Turner (Youtube)
C++ Weekly - Ep 241 - Using `explicit` to Find Expensive Accidental Copies

Support this channel and learn something new; buy my C++ Best Practices Book! https://leanpub.com/cppbestpractices

My Training Classes: https://emptycrate.com/training.html
Support these videos: https://www.patreon.com/lefticus
Follow me on twitter: https://twitter.com/lefticus