vendredi 27 octobre 2017

Why is this macro being passed three arguments?

#include <vector>

struct Foo { int a, b, c; };

int main()
{
    Foo myFoo = Foo{ 1, 2, 3 };

    std::vector<Foo> listOfFoos;
    listOfFoos.push_back(Foo{ 1, 2, 3 });


#define push(x) listOfFoos.push_back(x)

    push(Foo{ 1, 2, 3 } ); // Error

}

Errors are:

> "Expected a '}'"  
> "Syntax error: expected a ')' not '}'"  "Syntax
> error: missing ')' before ';'"

It took me ages on Visual Studio to try to figure out what was happening. It wasn't until I compiled on an online compiler using GCC that I got a more descriptive error:

error: macro "push" passed 3 arguments, but takes just 1

I guess I'm confused because I thought std::initializer_list is one struct, and should get passed as one. When it complains that 3 arguments as being passed to the macro is it saying by doing push({1, 2, 3}); I'm doing the equivalent of push(1, 2, 3);? This would seem that std::initializer_list does a type of expansion of its elements before passing it to the macro. I dont understand why this is. Also, I tried wrapping it in another set of brackets and it works:

push( ( {1, 2, 3} ) );

Aucun commentaire:

Enregistrer un commentaire