Sergey
Sergey

Reputation: 170

nested defines with defined parameters c++

Here's a smaller reproducer of my code:

#include <vector>
#include <iostream>

struct mystruct {
    int a;
    int param1;
    int param2;
};

#define mycase 5, 5

#define mytest_1(test) \
    mystruct{ 1, test }, \
    mystruct{ 2, test }

#define mytest_2(test) \
    mystruct{ 3, test }, \
    mystruct{ 4, test }

#define mytest_all(test) \
    mytest_1(test), \
    mytest_2(test)

void check(std::vector<mystruct> a) {
    for (int i = 0; i < a.size(); i++) {
        std::cout << i << ": " << a[i].a << " " << a[i].param1 << " " << a[i].param2 << std::endl;
    }
}

int main() {
    check(std::vector<mystruct>{mytest_1(mycase), mytest_2(mycase)});   // works fine
    check(std::vector<mystruct>{mytest_all(mycase)});                   // doesn't work

    return 0;
}

compiler produces the following errors (I'm using g++ 7.4.0):

test.cpp:32:50: error: macro "mytest_1" passed 2 arguments, but takes just 1
     check(std::vector<mystruct>{mytest_all(mycase)});
...                                                  ^
test.cpp:21:5: error: 'mytest_1' was not declared in this scope
     mytest_1(test), \
     ^
test.cpp:32:33: note: in expansion of macro 'mytest_all'
     check(std::vector<mystruct>{mytest_all(mycase)});
                                 ^~~~~~~~~~
... # some more errors

As far as I understand from the error message, it's because #define mycase 5, 5 consists of more than 1 argument, so mytest_all is being unfolded into something like this: mytest_1(5, 5).

Is there a way to define mytest_all in another way to make it work? Taking into account that i cannot change mytest_1. Thanks!

Upvotes: 2

Views: 159

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96334

Here's the solution:

#define IDENTITY(...) __VA_ARGS__

#define mytest_all(test) \
    mytest_1(IDENTITY(test)), \
    mytest_2(IDENTITY(test))

But if you could change mytest_1 and 2, a better option would be to make them use a .../__VA_ARGS__ parameter.

Upvotes: 1

Related Questions