static try catch construct would be helpful
Koroskin Denis
2korden+dmd at gmail.com
Wed Mar 26 08:02:24 PDT 2008
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
template SomeFunc(T)
{
static if (!is(T : Object)) // should only be invoked with reference
types
{
static throw new CT_Exception("Incompatible Type");
}
...
}
unittest
{
static try
{
alias SomeFunc!(int) SomeFuncInt;
SomeFuncInt();
static assert(false);
}
static catch(CT_AssertionFailureExpection e)
{
// failure
}
static catch(CT_Exception e)
{
pragma(msg, e.toString());
// success
}
}
More information about the Digitalmars-d
mailing list