简体   繁体   English

带有 #define 的 C++ 类型别名

[英]C++ type aliases with #define

I'm aware we can use typedef or using for making type aliases.我知道我们可以使用typedefusing来制作类型别名。 However, what about using #define ?但是,如何使用#define For example:例如:

#define integer int

Should I ever use this instead of using or typedef ?我应该使用它而不是usingtypedef吗?

Should I ever use this instead of using or typedef?我应该使用它而不是 using 或 typedef 吗?

Probably not.可能不是。 I do not know any case where a macro would be in any way better, but there are reasons why type aliases are objectively better.我不知道在任何情况下宏会以任何方式更好,但客观上来说类型别名更好是有原因的。 Most importantly, type aliases are enclosed by scopes.最重要的是,类型别名被作用域包围。

There is no reason to use a macro when you can not use a macro.当您不能使用宏时,没有理由使用宏。 Macros are not aware of scopes or namespaces.宏不知道作用域或命名空间。 Macros are replaced before actual compilation takes place, hence macros are not C++ entities.宏在实际编译发生之前被替换,因此宏不是 C++ 实体。 Consider for example:考虑例如:

#define integer int

struct Foo
{
    int integer;
};

GCC emits the following error message: GCC 发出以下错误消息:

<source>:5:5: error: multiple types in one declaration
    5 |     int integer;
      |     ^~~
<source>:1:17: error: declaration does not declare anything [-fpermissive]
    1 | #define integer int
      |                 ^~~
<source>:5:9: note: in expansion of macro 'integer'
    5 |     int integer;
      |         ^~~~~~~

because of the macro, the message is unnecessarily verbose.由于宏的原因,消息不必要地冗长。 While reading I have to follow the indirection via the macro to understand what is going on.在阅读时,我必须通过宏遵循间接性以了解发生了什么。

On the other hand, this:另一方面,这:

using integer = int;

struct Foo
{
    int integer;
};

Compiles without problems.编译没有问题。 Foo has a member called integer . Foo有一个名为integer的成员。 This is just one case out of millions where using a macro causes confusion.这只是数百万使用宏导致混淆的情况之一。

See here for what makes the difference.请参阅此处了解有何不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM