www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - HeadUnshared in core.atomic

reply "Mike Franklin" <none none.com> writes:
Hello,

I was recently exposed to this template in core.atomic:

private
{
     template HeadUnshared(T)
     {
         static if( is( T U : shared(U*) ) )
             alias shared(U)* HeadUnshared;
         else
             alias T HeadUnshared;
     }
}

Could someone please explain/elaborate on what this is doing, and 
why it's necessary and used so often in core.atomic?

Thanks,
Mike
Jun 11 2014
next sibling parent Andrew Edwards <ridimz yahoo.com> writes:
On 6/12/14, 1:29 AM, Mike Franklin wrote:
 Hello,

 I was recently exposed to this template in core.atomic:

 private
 {
      template HeadUnshared(T)
      {
          static if( is( T U : shared(U*) ) )
              alias shared(U)* HeadUnshared;
          else
              alias T HeadUnshared;
      }
 }

 Could someone please explain/elaborate on what this is doing, and why
 it's necessary and used so often in core.atomic?

 Thanks,
 Mike
Hello Mike, As to why it's necessary, I cannot really say. My only guess is that it will be used at a site that requires a pointer to shared data. Anyway, it simply observes the template parameter at compile time by creating a local variable U (or is U type?) and checking to see if it is a shared pointer. If it is, then it produces a pointer to the shared data: shared(U)* HeadUnshared; Note: in this re-designation, the pointer is not shared, just the data to which it points. Otherwise, it simply passes on the type: alias T HeadUnshared; For example if you instantiate with uint: HeadUnshared!uint p1; Then p1 is now a variable of type uint. The type is just forwarded. This would be the exact thing as: uint p1; However, if you use a shared pointer: HeadUnshared!(shared(uint*)) p2; The p2 is now a pointer to shared(uint). Also note that if you just pass a shared(type), you will get the same shared(type) in return. Hope that helps... someone more knowledgeable may be able to explain better.
Jun 12 2014
prev sibling parent "Sean Kelly" <sean invisibleduck.org> writes:
On Thursday, 12 June 2014 at 05:29:39 UTC, Mike Franklin wrote:
 Hello,

 I was recently exposed to this template in core.atomic:

 private
 {
     template HeadUnshared(T)
     {
         static if( is( T U : shared(U*) ) )
             alias shared(U)* HeadUnshared;
         else
             alias T HeadUnshared;
     }
 }

 Could someone please explain/elaborate on what this is doing, 
 and why it's necessary and used so often in core.atomic?
This is used to generate the return type when the return value is a copy of the input. This is of particular importance for operations like atomicLoad, whose purpose is to atomically obtain a local copy of a shared value.
Jun 12 2014