Gneric linkedList range adaptor

Paul Backus snarwin at gmail.com
Sat Feb 11 06:49:41 UTC 2023


On Friday, 10 February 2023 at 22:10:20 UTC, Ben Jones wrote:
> I'm trying to write a range adaptor for linked list types.  The 
> range type seems to work OK, but my helper function to deduce 
> the node type has a compiler error.  My hunch is that 
> `nextField` loses its association with T when I'm trying to 
> pass it as a template parameter inside the helper method, but I 
> can't use __traits(child) there to fix it.
>
> Any idea how to fix the helper method?

As a workaround, you can use a `string` instead of an `alias`:

```diff
--- before.d	2023-02-11 01:48:08.922945736 -0500
+++ after.d	2023-02-11 01:47:42.062922019 -0500
@@ -1,7 +1,7 @@
  import std.stdio;
  import std.range;

-struct LinkedListAdaptor(alias nextField, T){
+struct LinkedListAdaptor(string nextField, T){
   	T current;
      @safe:
     	nothrow:
@@ -19,11 +19,11 @@
      }

      void popFront() {
-		current = __traits(child, current, nextField);
+		current = __traits(getMember, current, nextField);
      }
  }

-auto linkedListAdaptor(alias nextField, T)(T head) if(is(T == 
U*, U)){
+auto linkedListAdaptor(string nextField, T)(T head) if(is(T == 
U*, U)){
   	return LinkedListAdaptor!(nextField, T)(head);

      //fails with:
@@ -39,8 +39,8 @@
  void main(){
  	Node* head = new Node(10, new Node(20, null));

-    auto rng1 = LinkedListAdaptor!(Node.next, Node*)(head);
-    auto rng = linkedListAdaptor!(Node.next)(head);
+    auto rng1 = LinkedListAdaptor!("next", Node*)(head);
+    auto rng = linkedListAdaptor!("next")(head);
      foreach(const x; rng){
          writeln(x.data);
      }
```


More information about the Digitalmars-d-learn mailing list