Decision on container design

Simen kjaeraas simen.kjaras at gmail.com
Sat Jan 29 03:01:51 PST 2011


Tomek Sowiński <just at ask.me> wrote:

> Michel Fortin napisał:
>
>> > Is there anything implementation specific in the outer struct that  
>> provides
>> > ref semantics to Impl? If not, Container could be generic,  
>> parametrized by
>> > Impl type.
>>
>> You could provide an implementation-specific version of some functions
>> as an optimization. For instance there is no need to create the Impl
>> when asking for the length, if the pointer is null, length is zero.
>> Typically, const function can be implemented in the outward container
>> with a shortcut checking for null.
>
> I think the reference struct can still be orthogonal to the container.
>
> 	struct Ref(Impl)
> 	{
> 		private Impl* _impl;
> 		ref Impl impl() @property
> 		{
> 			if (!impl) impl = new Impl;
> 			return *impl;
> 		}
>
> 		static if (hasLength!Impl)
> 		{
> 			auto length() @property
> 			{
> 				return impl ? impl.length : 0;
> 			}
> 		}
>
> 		alias impl this;
> 	}

Now, other functions may also exploit such a shortcut. How do you plan
to implement that?

Actually, by adopting another idiom, it can be done:

struct Ref(Impl) {
     private Impl* _impl;
     @property ref Impl impl() {
         return *(_impl = (_impl ? _impl : new Impl));
     }
     alias impl this;

     auto opDispatch(string name, T...)(T args) {
         mixin("return impl."~name~"(_impl,args);");
     }
}

struct ExampleImpl {
     static int length(ExampleImpl* that) {
         return that ? *that.actualLength : 0;
     }
     int actualLength( ) {
         return 42;
     }
}

Of course, I did not say it was a good idiom. :p

-- 
Simen


More information about the Digitalmars-d mailing list