What makes these few lines a small C ++ test environment?

Hi, I read through the implementation std::optional here , and I found the following lines in my module test files.

struct caller {
    template <class T> caller(T fun) { fun(); }
};
# define CAT2(X, Y) X ## Y
# define CAT(X, Y) CAT2(X, Y)
# define TEST(NAME) caller CAT(__VAR, __LINE__) = []

I really don't understand what these lines do. callerseems like a template for calling functions, but how can it be used like caller CAT ...? What does X ## Yit mean here? Later in the file, the user defines unit tests using TEST, but they are not displayed in any executable code (I mean that they are not called in the function mainat least), so I'm not even sure that the compiled binary actually runs the tests . Could you explain what is going on here? Thank you

Edit: Pretty sure the tests run when the binary is run, but how is this achieved?

+6
source share
1 answer

You can see the result after preprocessing ( -Efor gcc) ...

This is the code in which I added using a macro:

struct caller {
    template <class T> caller(T fun) { fun(); }
};
# define CAT2(X, Y) X ## Y
# define CAT(X, Y) CAT2(X, Y)
# define TEST(NAME) caller CAT(__VAR, __LINE__) = []

TEST(disengaged_ctor) { foo(); };

after preprocessing the last line turns into:

caller __VAR10 = []{ foo(); };

I am a little puzzled __VARand unused NAME*. However, it []{ foo(); }is a lambda, which when used to create callergets a call in the constructor caller.

* = , : , , __VAR10, 10 TEST(disengaged_ctor), .. NAME .

+10

All Articles