什么时候C ++宏是有益的? [英] When are C++ macros beneficial?

查看:103
本文介绍了什么时候C ++宏是有益的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 预处理程序有理由担心并被C ++社区忽略。内联函数,常量和模板通常是 #define 的更安全和更好的替代。

The C preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a #define.

巨集:

#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)  

不比类型安全更好:

inline bool succeeded(int hr) { return hr >= 0; }

但是宏有它们的位置,请列出宏找到的用法,不能不使用预处理器。

But macros do have their place, please list the uses you find for macros that you can't do without the preprocessor.

请将每个用例放在一个单独的答案中,以便可以投票,如果你知道如何实现一个答案,而没有预习者指出如何

Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.

推荐答案

作为调试函数的封装器,自动传递 __ FILE __ __ LINE __ ,etc:

As wrappers for debug functions, to automatically pass things like __FILE__, __LINE__, etc:

#ifdef ( DEBUG )
#define M_DebugLog( msg )  std::cout << __FILE__ << ":" << __LINE__ << ": " << msg
#else
#define M_DebugLog( msg )
#endif

这篇关于什么时候C ++宏是有益的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆