1

所以这是我的代码:

// Defines a tuple
#define __WINDOW__RESOLUTION__ 500, 200 

// Seperate the tuple
#define __WINDOW__X__1(Width, Height)  (Width)
#define __WINDOW__Y__1(Width, Height)  (Height)

// Add another sort of indirection because my tuple is a macro
#define __WINDOW__X__(Macro) __WINDOW__X__1(Macro)
#define __WINDOW__Y__(Macro) __WINDOW__Y__1(Macro)

// These should be the final values 500 and 200
#define __WINDOW__RESOLUTION__X__ (__WINDOW__X__(__WINDOW__RESOLUTION__))
#define __WINDOW__RESOLUTION__Y__ (__WINDOW__Y__(__WINDOW__RESOLUTION__))

当我使用最终数字应该是的第一个宏时,似乎出了点问题:

std::cout << __WINDOW__RESOLUTION__X__ << std::endl; // Outputs 200 instead of 500

上面的行输出数字 200,所以 Y 值而不是 X 值

std::cout << __WINDOW__RESOLUTION__Y__ << std::endl; // ERR with macro underlined

这一行甚至无法编译 [C2059,语法错误:“)”]

谢谢你帮助我亚历克斯

4

2 回答 2

2

作为记录 - 我知道您的解决方案是“不要这样做”,但我仍然想为原始问题提供答案。

事实上,我实际上没有看到您的代码有任何问题。如果您使用像这样的基本测试示例编译它,它实际上可以正常工作:

// Defines a tuple
#define __WINDOW__RESOLUTION__ 500, 200 

// Seperate the tuple
#define __WINDOW__X__1(Width, Height)  (Width)
#define __WINDOW__Y__1(Width, Height)  (Height)

// Add another sort of indirection because my tuple is a macro
#define __WINDOW__X__(Macro) __WINDOW__X__1(Macro)
#define __WINDOW__Y__(Macro) __WINDOW__Y__1(Macro)

// These should be the final values 500 and 200
#define __WINDOW__RESOLUTION__X__ (__WINDOW__X__(__WINDOW__RESOLUTION__))
#define __WINDOW__RESOLUTION__Y__ (__WINDOW__Y__(__WINDOW__RESOLUTION__))

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    std::cout << __WINDOW__RESOLUTION__X__ << std::endl;
    std::cout << __WINDOW__RESOLUTION__Y__ << std::endl;
    return 0;
}

不过,看起来您的错误可能与您 last 中的括号有关macro,因此只需删除它们就可以解决这个问题,但同样 - 这对我来说不是必需的(使用gcc 5.4under ubuntu):

// These should be the final values 500 and 200
#define __WINDOW__RESOLUTION__X__ __WINDOW__X__(__WINDOW__RESOLUTION__)
#define __WINDOW__RESOLUTION__Y__ __WINDOW__Y__(__WINDOW__RESOLUTION__)

之前也有人指出,双下划线__后跟一个大写字母是保留的,但它肯定不会停止gcc编译它——虽然它可能会在更严格的编译标志下产生错误!

于 2016-07-17T08:53:41.207 回答
2

使用 gcc4.9 编译时似乎工作正常,但问题可能在于编译器线程__WINDOW__RESOLUTION__作为单个参数。例如,如果您更换

#define __WINDOW__RESOLUTION__X__ (__WINDOW__X__(__WINDOW__RESOLUTION__))

#define __WINDOW__RESOLUTION__X__ (__WINDOW__X__(500, 200))

它将抛出一个错误,因为__WINDOW__X__只需要 1 个参数。

您可以通过在宏中使用...and来解决此问题__VA_ARGS__,该宏将转发它收到的任何参数:

#define __WINDOW__X__(...) __WINDOW__X__1(__VA_ARGS__)
#define __WINDOW__Y__(...) __WINDOW__Y__1(__VA_ARGS__)
于 2016-07-17T09:55:03.667 回答