refInt = ref int: how to achieve this? or is this a bug?
Avrina
avrina12309412342 at gmail.com
Wed Jun 17 21:49:29 UTC 2020
On Wednesday, 17 June 2020 at 21:27:01 UTC, mw wrote:
> On Wednesday, 17 June 2020 at 20:47:59 UTC, Steven
> Schveighoffer wrote:
>> Essentially, your alias statement becomes:
>>
>> alias refInt = int;
>>
>> Which in itself is somewhat of a "feature", as storage classes
>> that do not apply are ignored. Some may consider it a bug, but
>> I haven't seen anyone attempt something like what you have, it
>> sure seems like the compiler should complain.
>
> I would consider it a bug, *even* C++ can handle this better
> :-) i.e. no surprise to the programmer.
>
> cat reft.cpp
> ----------------------
> #include <stdio.h>
>
> typedef int& refInt;
>
> void f(refInt i) {
> i = 456;
> }
>
> int main() {
> int i = 123;
> printf("%d\n", i);
> f(i);
> printf("%d\n", i);
> }
> ----------------------
>
> $ make reft
> g++ reft.cpp -o reft
>
>
> $ ./reft
> 123
> 456
It's not a bug, it is purposefully designed to be that way.
Just like you can't do ref variables.
void main() {
int a;
int& b = a; // ok C++
ref int c = a; // not valid D
}
You can do something like this instead, not sure what you are
trying to do tho. Could just be easier to put a separate function
in the `static if` that you are trying to define the ref type in
instead.
import std.stdio;
void foo(T)(auto ref T v) if (is(T : int) == __traits(isRef, v)) {
writeln(__traits(isRef, v) ? "by ref" : "by value");
}
void main() {
int a;
foo(a); // by ref
// foo(10); // error by value
float b;
// foo(b); // error by ref
foo(10.0f); // by value
}
More information about the Digitalmars-d
mailing list