Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda within assert

Tags:

c++

assert

lambda

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

like image 276
Juarrow Avatar asked Oct 25 '25 04:10

Juarrow


2 Answers

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;
    })());
like image 94
eq- Avatar answered Oct 26 '25 16:10

eq-


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.

like image 45
Mike Seymour Avatar answered Oct 26 '25 16:10

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!