static try catch construct would be helpful
Bruno Medeiros
brunodomedeiros+spam at com.gmail
Thu Mar 27 11:58:49 PDT 2008
Koroskin Denis wrote:
> On Wed, 26 Mar 2008 16:30:53 +0300, Bruno Medeiros
> <brunodomedeiros+spam at com.gmail> wrote:
>
>> Bill Baxter wrote:
>>> Currently, the best way I've found to conditionalize that is:
>>> static if(is(typeof(_inner.doSomething(1,1,1,1)))) {
>>> void doSomething(int a, int b, int c, int d)
>>> {
>>> _inner.doSomething(a,b,c,d);
>>> // do something else here
>>> }
>>> }
>>> Maybe there's a better way to write that one.. I'm not sure. But
>>> the signature of the thing that may or may not exist can be
>>> arbitrarily complex. It becomes difficult to think of an
>>> is-expression that can test for what you want.
>>
>> I don't understand this. Why is it difficult to use an is-expression
>> to test the condition you are checking? If you're just checking to see
>> if a member exists, you can just do
>> static if(is(typeof(_inner.doSomething))) {
>> If you're checking for the existence of a particular overload, then
>> you will need an expression where that function overload is called.
>> Perhaps the problem is code duplication? (like having two function
>> calls, such as "_inner.doSomething(1,1,1,1)" and
>> "_inner.doSomething(a,b,c,d)" ?
>>
>
>
> Well, I can think of a more sophisticated examples:
>
> template invert(real arg)
> {
> const real invert = 1/arg;
> }
>
> unittest
> {
> static try
> {
> real success = invert!(1);
> real failure = invert!(0);
> static assert(false); // should not get here
> }
> static catch (CT_DivideByZeroException e) // CT for Compile-Time
> {
> pragma(msg, e.toString()); // should print DivideByZeroException
> }
> }
>
> template wrong_factorial(int i)
> {
> const int wrong_factorial = i * wrong_factorial!(i-1);
> }
>
> unittest
> {
> static try
> {
> const int f = wrong_factorial!(1);
> static assert(false);
> }
> static catch (CT_Exception e)
> {
> pragma(msg, e.toString()); // should print "CT Stack overflow"
> or "CT Nested loop is too deep"
> }
> }
>
> or even
>
The divide by zero case actually works with an is-expression (that is,
the is-expression returns false if such compile time error occurs
there). I don't think it's something that is clearly defined in the spec
tough, so I don't know how much this behavior can be relied on.
The wrong factorial case on the other hand, doesn't work. If it is in an
is-expression there will always be a recursive expansion compiler error.
In any case, I see little or no usefulness in being able to detect/catch
such extreme compiler errors. It just seems bad structure, and it is
something that not even in runtime I would recommend doing (catching
Divide by Zero or Stack Overflow errors).
--
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list