Returning const? -- A potential solution

Jason House jason.james.house at gmail.com
Sat Mar 7 19:44:48 PST 2009


The ugly const thread got me thinking about the old problem of returning an 
input while preserving const safety.  I have an idea that seems 
reasonable...

In a nutshell, I'm thinking that const(T) should be a base type for T, 
immutable(T) and return(T).  return(T) is treated in a read-only fashion, 
just like const(T) and immutable(T). Here are some of the key things I think 
this achieves:
  * Input arguments are never mutated
  * Use of input parameters in calls to functions as const(T) is 100% legal.
  * Temporary variables can legally be defined and used
  * Calling other functions that return return(T) is allowed
  * No code duplication
  * No code bloat (compiler only needs to generate one version of the code)
  * Functions can be virtual

Let's take a relatively simple example: max

return(T) max(return(T) a, return(T) b){ return (a>b)?a:b; }

When max is called, the compiler would examine the inputs for a and b to 
determine what the true type for return(T) is from the callee's 
perspective...  So a call with T and immutable(T) would use const(T) as the 
perceived return type while an argument of T and T would use T as the return 
type.

At the call site, the compiler would ensure type safety of how the return 
type is used.  Within max, the compiler would ensure that the arguments are 
either treated as const(T) in function calls but not mixed with with types 
T, const(T), or immutable(T)

PS: The return(T) notation is an arbitrary one for the purposes of this 
post.  We need a technical solution before worrying about the color of the 
bicycle shed




More information about the Digitalmars-d mailing list