I am trying to create a matching mechanism for the new std::optional<T>in C ++. I wrote the following macro:
#define EXPAND(x) x
#define CAT_(x, y) x##y
#define CAT(x, y) CAT_(EXPAND(x), EXPAND(y))
#define if_opt__(xalt, bval, x, y) \
auto xalt = y; \
bool bval = true; \
if (xalt.has_value()) \
for (auto x = xalt.value(); bval; bval = false)
#define if_opt_(xalt, x, y) if_opt__(xalt, CAT(xalt, _b), x, y)
#define if_opt(x, y) if_opt_(CAT(x, __LINE__), x, y)
And I created the following sample program for it:
std::optional<int> get(int a) {
if (a < 0) {
return {};
}
return a;
}
int main(void) {
if_opt(a, get(0)) {
std::cout << "optional matched!" << std::endl;
}
return 0;
}
However, when I try to compile a program, I get errors such as' redefinition; different base types. "Then I pre-processed it into a file, copied the result and compiled it and worked fine. Macro rated for:
auto a24 = get(0);
bool a24_b = true;
if (a24.has_value())
for (auto a = a24.value(); a24_b; a24_b = false) {
std::cout << "optional matched!" << std::endl;
}
Why doesn't it compile using the macro itself? I am using MSVC.
source
share