C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Bool casting operator to check if a container not empty

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Thu, 19 Oct 2023 18:28:21 +0200
Hi Marcin,   one could (from a logical, not a C++ language rules standpoint) see a container implicitly converting to the number of elements in them. And then the number of elements to true, if larger than zero.   But still, there is a difference between an invalid pointer and an empty container. It is not the same. E.g.   class MyContainerLikeClass { public:     int& get(int idx) { return _inner[idx] };     operator bool() { return _inner.size > 0; };   private:     std::vector<int> _inner; };   MyContainerLikeClass container1;   // test for at least one element? if (container1)     std::cout << container1.get(0) << std::endl;     MyContainerLikeClass* container2 = nullptr;   // test for valid pointer if(container2)     std::cout << container2->get(0) << std::endl; // this line can be UB     // test for valid pointer and for at least one element if(container2 && *container2)     std::cout << container2->get(0) << std::endl; // this line is safe     After proving the difference:   Even then, adding operator bool to the containers would generally work as shown. The question is,  whether this is too confusing or typical (or should be) for std library classes to show their size as implicit bool or implicit int.     -----Ursprüngliche Nachricht----- Von:Marcin Jaczewski via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Do 19.10.2023 12:40 Betreff:Re: [std-proposals] Bool casting operator to check if a container not empty An:std-proposals_at_[hidden]; CC:Marcin Jaczewski <marcinjaczewski86_at_[hidden]>; Bo Persson <bo_at_[hidden]>; ``` if (vect) foo(vect[0]); if (ptr) foo(ptr[0]); ``` Both are equivalent. At least in my code base I use the `bool` operator like this.  

Received on 2023-10-19 16:28:23