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; }
as opposed to
#define LOGFN( T ) void log_type( const T value ) { std::cout << #T ## ": " << value; }
LOGFN( int )
LOGFN( bool )
...
LOGFN( char )
LOGFN( double )
LOGFN( float )
Any other 'irreplaceables'?
EDIT: 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.
- 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)