Neat trick - 'with' and unnamed objects + 'with' proposals

BCS BCS at pathlink.com
Tue Apr 24 08:59:02 PDT 2007


Bill Baxter wrote:
> I just discovered this little trick that I think is way cool.
> You can use 'with' in combination with an anonymous object to set 
> attributes on that object without having to bother giving it a name or a 
> variable.
> 
> 
> with(new someGUIWidget(myParent)) {
>    shown = true;
>    focusable = false;
> }
> 
> That's really nifty for GUI code.
> 
> This could be even more useful if there were some kind of 'this' for 
> 'with' blocks.  Then you could also call non-member functions.
> 
> with(new someGUIWidget(myParent)) {
>    shown = true;
>    focusable = false;
>    some_global_function(this);
> }
> 
> Or perhaps analogous to how constructors are called 'this()' and have a 
> 'this' pointer, we'd have a 'with' pointer so that the meaning of 'this' 
> in a class wouldn't be shadowed:
> 
> with(new someGUIWidget(myParent)) {
>    some_global_function(with);
> }
> 
> And even cooler would be if you could have a 'with-expression' that just 
> evaluates to the thing in the parens:
> 
> auto obj = with(new someGUIWidget(myParent))
> {
>    shown = true;
>    focusable = false;
>    some_global_function(this);
> };
> 
> 
> Sometimes I've seen people try to make APIs in C++ where all the 
> attribute setters return the object so that property setting can be 
> chained, like:
> 
>      myObject.set_focusable(true).set_shown(true);
> 
> Presumably the objective is to avoid repeating the name of the object a 
> lot.  But that never works out too well, because making every mutator 
> return a pointer to 'this' is just not so practical in the end, and 
> forcing every property setting operation to use function call syntax is 
> also not so great.
> 
> --bb


how about take a trick from "if"

with(auto name = new someGUIWidget(myParent))
{
    shown = true;
    focusable = false;
    some_global_function(name);
}



More information about the Digitalmars-d mailing list