Is it possible to create an object and call a method in one expression?

So, in order not to be blamed for the XY problem , here is the full picture:

I am implementing doctest , and the current function I want is INFO(). It works as follows:

int var1 = 1;
{
    int var2 = 666;
    INFO(var1 << "some string" << var2); // INFO is a macro
    // random code...
    CHECK(var1 == 42); // only if this fails should we see the INFO text
}
CHECK(var1 == 42); // INFO is scoped and should not be relevant here

It is easy. I want, however, 2 more things in addition to this simple behavior:

  • I need a lazy string construction - only if the statement fails
  • I do not want ANY distributions (at least for a small number of variables passed in INFO()). I want to use the stack (using something like optimizing a small buffer). Note that I hold stack pointers with objects for stringing, not actual strings. Also, in the case of C ++ 11 rvalue references, I remove the overload operator<<for &&, so no rvalues ​​can bind to it, since I keep pointers.

I did by doing both of these things, but noticed that my macro is INFO()not a single expression. This is a transaction breaker - and I can't wrap it all up inside do { ... } while(false)to make it one of the operators, because INFO()- scope - that's all for that ...

Here is the macro INFO():

#define INFO_IMPL(name, x) InfoBuilder name; name << x
#define INFO(x) INFO_IMPL(anon_name, x)

Catch INFO() , this, , , operator<<, , , .

ScopedMessage anon_name = MessageBuilder() << x; // simplification

, operator<<.

, - .

, ? - :

InfoBuilder info() << x

++ 98.

( , ) - ++...

struct Y;

struct X {
    X(Y&){}
};

struct Y {
    Y(X&, int){}
};

int main() {
    X x(Y(x, 6));
}
+4
1

, .

X , Y, Y - :

Y lvalue = X() << arg1 << arg2;

, @Remy Lebeau - , Catch, "" ( ) InfoBuilder InfoScope - InfoBuilder.

#define INFO(x) InfoScope ANONYMOUS(_CAPTURE_)(InfoBuilder() << x)

, ...

0

Source: https://habr.com/ru/post/1673061/


All Articles