Can std.variant be used with std.container.rbtree?

Salih Dincer salihdb at hotmail.com
Sat Apr 2 14:23:31 UTC 2022


On Friday, 1 April 2022 at 22:22:21 UTC, Vijay Nayar wrote:
>
> A `RedBlackTree` constructs and runs perfectly fine using "int" 
> as the data type, but it seems to blow up as soon as I use 
> `std.variant : Variant`.
>
> ```
> Compilation output (1: )
>
> /dlang/dmd/linux/bin64/../../src/phobos/std/container/rbtree.d(1116): Error: `@safe` function `std.container.rbtree.RedBlackTree!(VariantN!32LU, "a < b", false).RedBlackTree.toHash` cannot call `@system` function `std.container.rbtree.RBRange!(RBNode!(VariantN!32LU)*).RBRange.front`
> /dlang/dmd/linux/bin64/../../src/phobos/std/container/rbtree.d(682):        `std.container.rbtree.RBRange!(RBNode!(VariantN!32LU)*).RBRange.front` is declared here
> /dlang/dmd/linux/bin64/../../src/phobos/std/container/rbtree.d(1116): Error: destructor `std.variant.VariantN!32LU.VariantN.~this` is not `nothrow`
> /dlang/dmd/linux/bin64/../../src/phobos/std/container/rbtree.d(1113): Error: function `std.container.rbtree.RedBlackTree!(VariantN!32LU, "a < b", false).RedBlackTree.toHash` may throw but is marked as `nothrow`
> onlineapp.d(10): Error: template instance 
> `std.container.rbtree.RedBlackTree!(VariantN!32LU, "a < b", 
> false)` error instantiating
> ```

If your type includes opCmp() there is no reason not to use 
rbTree.  Let me give a simple example:
```d
struct Char {
   char c;
   auto opCmp(Char rhs) const {
     return c == rhs.c ? 0: c - rhs.c;
   }
}

import std.container.rbtree;
import std.stdio;
void main() {
   alias Type = Char;

   with(new RedBlackTree!(Type))
   {
     stableInsert(Type('B'));
     stableInsert(Type('A'));
     stableInsert(Type('C'));
     foreach (v; upperBound(Type('A')))
       v.c.write(", ");
     writeln; // "B, C, "
   }
}
```
SDB at 79


More information about the Digitalmars-d-learn mailing list