什么是预处理器宏有好处? [英] What are preprocessor macros good for?
问题描述
在阅读另一个有关使用宏的问题后,我想知道:是什么?
After reading another question about the use of macros, I wondered: What are they good for?
看到被任何其他语言结构替换很快就是减少需要在下面输入的相关词的数量:
One thing I don't see replaced by any other language construct very soon is in diminishing the number of related words you need to type in the following:
void log_type( const bool value ) { std::cout << "bool: " << value; }
void log_type( const int value ) { std::cout << "int: " << value; }
...
void log_type( const char value ) { std::cout << "char: " << value; }
void log_type( const double value ) { std::cout << "int: " << value; }
void log_type( const float value ) { std::cout << "float: " << value; }
而不是
#define LOGFN( T ) void log_type( const T value ) { std::cout << #T ## ": " << value; }
LOGFN( int )
LOGFN( bool )
...
LOGFN( char )
LOGFN( double )
LOGFN( float )
任何其他不可替代品?
试图总结原因 - 为什么在答案中遇到;因为这是我感兴趣的主要是因为我有一种感觉,他们大多是由于我们仍然在原始文本文件,仍然,支持不佳的环境中编程。
trying to summarize the reasons-why encountered in the answers; since that's what I was interested in. Mainly because I have a feeling that most of them are due to us still programming in raw text files in, still, poorly supporting environments.
- 编译代码的灵活性(例如
#ifdef DEBUG
,平台问题)(SadSido,Catalin,Goz) - 调试目的(例如
__ LINE__,__TIME __
);我也把'stringifying'在这个原因下(SadSido,Jla3ep,Jason S) - PHP的
require 与
包含
功能(#pragma once
) (SadSido,Catalin) - 通过替换复杂的代码(例如
MESSAGEMAP
,BOOST_FOREACH
)(SadSido,fnieto) - DRY原则(Jason S)
- 内嵌替换(Matthias Wandel,Robert S. Barnes)
- stringifying(Jason S)
- flexibility of code-to-be compiled (e.g.
#ifdef DEBUG
, platform issues) (SadSido, Catalin, Goz) - debug purposes (e.g.
__LINE__, __TIME__
); I also put 'stringifying' under this reason (SadSido, Jla3ep, Jason S) - replacing e.g. PHP's
require
vs.include
feature (#pragma once
) (SadSido, Catalin) - readability enhancement by replacing complicated code (e.g.
MESSAGEMAP
,BOOST_FOREACH
) (SadSido, fnieto) - DRY principle (Jason S)
- an inline replacement (Matthias Wandel, Robert S. Barnes)
- stringifying (Jason S)
推荐答案
$ b
#ifdef __DEBUG __
); #pragma once
); __ FILE __
和 __ LINE __
- 由当前文件名和当前行替换; BEGIN_MESSAGE_MAP ()
); - compile different code under different conditions (
#ifdef __DEBUG__
); - guards to include each header once for each translation unit (
#pragma once
); __FILE__
and__LINE__
- replaced by the current file name and current line;- structuring the code to make it more readable (ex:
BEGIN_MESSAGE_MAP()
);
查看有趣的宏观讨论,请访问:
See interesting macro discussion at gotw here:
http://www.gotw.ca/gotw/032.htm
http:// www .gotw.ca / gotw / 077.htm
这篇关于什么是预处理器宏有好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!