Juarrow
Juarrow

Reputation: 2404

Lambda within assert

is it somehow possible to use a lambda within a call to assert() ?

When i try the following...

assert([&]() -> bool{
        sockaddr_storage addr; int addrlen = sizeof(addr);
        return (getsockname(this->m_Socket, (sockaddr*)&addr, &addrlen) != 0) ? false : true;
    });

... i get the error

error C2675: unary '!' : '`anonymous-namespace'::' does not define this operator or a conversion to a type acceptable to the predefined operator

Upvotes: 4

Views: 1734

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254631

You can't assert that the lambda itself is "true", since lambdas have no concept of truthiness.

If you want to invoke the lambda and assert that its return value was true, then you need to invoke it:

assert([&]() -> bool{
    sockaddr_storage addr; int addrlen = sizeof(addr);
    return getsockname(this->m_Socket, (sockaddr*)&addr, &addrlen) == 0;
}());
 ^^

I've also changed the second line of the lambda into something that makes a little more sense than your code.

Upvotes: 4

eq-
eq-

Reputation: 10096

Sure, but assert really only wants a boolean; not a lambda, so you'll have to call it yourself (this assuming that your lambda is one that returns something you want to assert):

assert(([&]() -> bool{
        sockaddr_storage addr; int addrlen = sizeof(addr);
        return getsockname(this->m_Socket, (sockaddr*)&addr, &addrlen) == 0;
    })());

Upvotes: 11

Related Questions