Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ how to assert that all std::shared_ptr in a vector are referring to something

When I have a function receiving a (smart) pointer that is supposed to refer something, I always start as follows:

class Foo;
void doSomething(const std::shared_ptr<Foo>& pFoo)
{
    assert(pFoo);
    // ...
}

Now I am looking for a similar assert condition for a vector (or other container) of (smart) pointers. The best I could come up with is:

void doSomething(const std::vector<std::shared_ptr<Foo> >& pFoos)
{
    assert(std::all_of(pFoos.begin(), pFoos.end(), [](const std::shared_ptr<Foo>& pFoo) { return pFoo; }));
    // ...
}

I wonder whether this could be improved.. can the lambda be avoided? (I tried to use the get() method of shared_ptr but template deduction fails then) Or is there another way to assert for a whole container?

like image 607
mr_T Avatar asked Dec 08 '16 10:12

mr_T


2 Answers

one more way to do it:

assert(std::find(pFoos.begin(), pFoos.end(), nullptr) == pFoos.end());
like image 166
Sandro Avatar answered Sep 22 '22 17:09

Sandro


Another slightly convoluted way to express it with standard functionality only:

assert(std::none_of(pFoos.begin(), pFoos.end(), std::logical_not<std::shared_ptr<Foo>>{}));

From C++14 onwards, you can use the generic specialization of std::logical_not:

assert(std::none_of(pFoos.begin(), pFoos.end(), std::logical_not<>{}));
like image 25
Quentin Avatar answered Sep 25 '22 17:09

Quentin