3

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

4

2 回答 2

10

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;
    })());
于 2012-08-17T17:33:03.353 回答
3

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.

于 2012-08-17T17:35:46.373 回答