Const initialization issue, looking for solution

Jakob Ovrum jakobovrum at gmail.com
Wed May 29 08:32:14 PDT 2013


On Wednesday, 29 May 2013 at 15:11:53 UTC, Andrei Alexandrescu 
wrote:
> I must have missed part of this - how would the desired setup 
> work?
>
>
> Andrei

Maybe something like the following would work. collectException's 
return value and out parameter have been swapped for 
demonstration - an out parameter for the result just moves the 
problem to the body of collectException:
----
// Can throw, and we want to catch
int createTheVar();

// Can also throw, but we don't want to catch it here
int transform(int a);

int foo()
{
	Exception e;
	const(int) i = collectException(createTheVar(), e);

	if(e)
		// Exception handling code

	return transform(i);
}
----
By removing the scope created by try-catch, the variable can be 
declared and initialized at the same time, satisfying the 
requirements of const/immutable. Further, the transform() call is 
left unguarded as specified.

Such a collectionException works because it can use `return` 
inside the try scope without broadening what it catches:
----
E collectException(T = Exception, E)(lazy E exp, out T ex)
{
	try
		return exp();
	catch(T e)
	{
		ex = e;
		return E.init; // Kind of a drawback
	}
}
----
So, I guess using another function to do the try-catch is a 
workable solution.


More information about the Digitalmars-d mailing list