简体   繁体   中英

C++ type aliases with #define

I'm aware we can use typedef or using for making type aliases. However, what about using #define ? For example:

#define integer int

Should I ever use this instead of using or typedef ?

Should I ever use this instead of using or 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. Consider for example:

#define integer int

struct Foo
{
    int integer;
};

GCC emits the following error message:

<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 . This is just one case out of millions where using a macro causes confusion.

See here for what makes the difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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