Is there a way to replace Exception with as a macro in C?
Marco de Wild
admin at localhost.com
Tue Feb 19 06:21:43 UTC 2019
On Tuesday, 19 February 2019 at 05:50:04 UTC, yisooan wrote:
> I wonder there is the way as I said in the title. For instance,
> in C,
>> #define indexInvalidException Exception("The index is invalid")
>> /* Do something with the macro here */
>> if (false)
> This is allowed.
> But I want to do the exact same thing in D. I have already
> tried some expressions with alias? but it doesn't work.
>> alias indexInvalidException = Exception("The index is
>> /* Use the alias in somewhere */
>> if (false)
>> throw new indexInvalidException;
> Would you help me, please?
Alias is just a nickname for a symbol (i.e. alias string =
immutable(char);) and lets you refer to that symbol with the
nickname. You can't supply runtime parameters (like constructor
parameters), but you can give compile-time template parameters
(as the result of applying those parameters is a symbol rather
than a value). Macros on the other hand, do a textual
replacement, i.e. they alter the source code that goes into the
Depending on how brief you want to make your code, you can either
use classic inheritance
class IndexInvalidException : Exception
super("The index is invalid")
or, closest as you can get to macros:
enum throwNewIndexInvalidException = `throw new Exception("The
index is invalid");`;
String mixins transform a string into an expression, and paste
the expression wherever it is mixed in. It gets precompiled
rather than substituted in the source code. This means it's best
to have the whole line into a string, instead of individual parts
(you can't have a mixin with just `Exception("The index is
invalid")` for example).
More information about the Digitalmars-d-learn