On Sunday, 18 November 2018 at 17:30:18 UTC, Dennis wrote:
I'm making a fixed point numeric type and want it to work correctly with const. First problem:

```
const q16 a = 6;
a /= 2;          // compiles! despite `a` being const.
writeln(a);      // still 6
a.toQ32 /= 2;    // what's actually happening
```

My q16 type has an implicit conversion to q32 (like how int can be converted to long):
```
q32 toQ32() const {
  return q32(...);
}
alias toQ32 this;
```
How do I make it so that a const(q16) will be converted to a const(q32) instead of mutable q32?

Second problem:
```
Q log2(Q)(Q num) if (is(Q : q16) || is(Q : q32)) {
    import std.traits: Unqual;
    Unqual!Q x = num;
    // actual code
}
```
When I call this with a const(q16), Q is resolved to const(q16) so I have to unqualify Q every time. It works, but feels clumsy. Is there an easier way to automatically de-const parameters? We're working with small value types here, it should be simple.

If anyone knows any other pitfalls with const, I'd love to know them.

Yah most people tend to avoid const for this reason. It only really works for basic types, if you have a "const int" you can convert it to an "int" by copy. But if you have a type like Vector!(const int) that won't work, you can't even convert Vector!int to Vector!(const int) easily for example.

```
Q log2(Q)(Q num) if (is(Q : q16) || is(Q : q32)) {
    import std.traits: Unqual;
    Unqual!Q x = num;
    // actual code
}
```

This is pretty much the only way, you can just add

alias V = Unqual!Q;

then use V in your function instead of Unqual!Q everywhere.

Reply via email to