提供给类函数宏调用的参数过多

2022-01-11 00:00:00 macros c++

假设我们有一个 std::aligned_storage 的实现.我为 alignofalignas 运算符定义了两个宏.

Say we have an implementation of std::aligned_storage. I've defined two macros for the alignof and alignas operators.

#include <iostream>
#include <cstddef>

#define ALIGNOF(x) alignof(x)
#define ALIGNAS(x) alignas(x)

template<std::size_t N, std::size_t Al = ALIGNOF(std::max_align_t)>
struct aligned_storage
{
    struct type {
        ALIGNAS(Al) unsigned char data[N];
    };
};

int main()
{
    // first case
    std::cout << ALIGNOF(aligned_storage<16>::type); // Works fine

    // second case
    std::cout << ALIGNOF(aligned_storage<16, 16>::type); // compiler error
}

在第二种情况下,我得到问题标题中的错误(使用 Clang 编译,使用 GCC 时出现类似错误).如果我分别用 alignofalignas 替换宏,则不会出现错误.这是为什么?

In the second case I get the error in the title of the question (compiling with Clang, similar error with GCC). The error is not present if I replace the macros with alignof and alignas respectively. Why is this?

在你开始问我为什么要这样做之前 - 原始宏具有 C++98 兼容代码,例如 __alignof__attribute__((__aligned__(x))) 并且这些是特定于编译器的,所以宏是我唯一的选择...

Before you start asking me why I'm doing this - the original macros have C++98 compatible code such as __alignof and __attribute__((__aligned__(x))) and those are compiler specific, so macros are my only choice...

因此,根据标记为重复的问题,额外的一组括号将解决该问题.

So according to the question marked as duplicate, an extra set of parenthesis would fix the issue.

std::cout << ALIGNOF((aligned_storage<16, 16>::type)); // compiler error

它没有.那么,我该怎么做呢?(令人满意的问题?)

It doesn't. So, how would I go about doing this? (Satisfiable question?)

推荐答案

C/C++ 预处理器不知道任何 C/C++ 语言结构,它只是具有自己的语法和规则的文本预处理器.根据该语法,以下代码 ALIGNOF(aligned_storage<16, 16>::type) 是使用 2 个参数调用宏 ALIGNOF (aligned_storage<16code> 和 16>::type) 因为括号内有逗号.

C/C++ preprocessor is not aware of any C/C++ language constructs, it is just text preprocessor with its own syntax and rules. According to that syntax the following code ALIGNOF(aligned_storage<16, 16>::type) is invocation of macro ALIGNOF with 2 arguments (aligned_storage<16 and 16>::type) because there is comma inside parentheses.

我建议您 typedef aligned_storage<16, 16> 并在此宏调用中使用该类型.

I would suggest you to typedef aligned_storage<16, 16> and use that type inside this macro invocation.

相关文章