Uphill

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 1 09:56:59 PDT 2015


On Monday, 1 June 2015 at 16:09:34 UTC, Dan Olson wrote:
> "Atila Neves" <atila.neves at gmail.com> writes:
>
>> On Sunday, 31 May 2015 at 09:13:33 UTC, Ola Fosheim Grøstad 
>> wrote:
>>> On Sunday, 31 May 2015 at 08:51:00 UTC, Atila Neves wrote:
>>>> While C++ programmers should try and avoid the preprocessor 
>>>> as much
>>>> as possible, sometimes it just isn't possible to do so. 
>>>> There's
>>>> just no other way to generate code sometimes. I know, I've 
>>>> tried.
>>>
>>> In what case is this true? If it is only to avoid some boiler 
>>> plate
>>> then it is not a good excuse, IMO. You can usually avoid 
>>> macros by
>>> restructuring composition (using multiple layers of 
>>> templates).
>>
>> I'll take a macro over boilerplate any day of the week and 
>> twice on
>> Sundays.
>
> Timely!  I and stack overflow struggled for a couple hours to 
> find an
> equivalent C++ template for something that was straightforward 
> with a
> couple macros.

I use macros for stuff like exceptions all the time - e.g.

THROW(MyException, ("This value is wrong: %d", foo));

The macro handles logging the exception, getting and setting the 
stacktrace on the exception, setting the file and line number of 
the exception, as well as constructing the string for the 
exception's message given the arguments - and of course finally 
throwing it. You _are_ still forced to call format in D (whereas 
that macro does it for you), but aside from that, the built-in 
exception stuff does all of that for you by simply throwing a new 
exception with a message, whereas C++ doesn't even come close. 
Without a macro, getting all of the information in C++ - and 
doing it consistently and correctly - would be a big problem.

Yes, macros should be avoided in general, but there are areas 
where you really don't have much choice, and saying that all 
macros are unequivocably bad is quite short-sighted. It's when 
macros are used when they aren't needed that it's a problem.

Coming out of college, I actually believed the dogma that all 
macros are bad, but experience has shown me that that's just not 
true. Sure, it would be nice if we had a better solution in C++, 
but sometimes we just don't.

- Jonathan M Davis


More information about the Digitalmars-d mailing list