digitalmars.D.learn - "if" is not evaluated for fields of Class.tupleof
- Timoses (37/37) May 19 2017 Hey there,
- ag0aep6g (4/9) May 19 2017 You probably want `static if` here.
- Timoses (13/13) May 22 2017 The easiest way is probably casting:
- Stanislav Blinov (5/18) May 23 2017 Don't cast arbitrary types to classes, you're going to stumble
Hey there,
trying to read data into the fields of a class.
This is what I got so far:
```
import std.traits;
import std.bitmanip;
class Test {
byte[4] marray;
byte mbyte;
this(ubyte[] data)
{
auto fields = this.tupleof;
foreach (field; fields)
{
// Here it should actually not enter when field is
mbyte (byte)
if (isStaticArray!(typeof(field)))
{
for (int i = 0; i < field.length; i++)
field[i] = data.read!(typeof(field[i]));
}
else
{
}
}
}
}
void main() {
new Test([0x12, 0x23, 0x34, 0x45, 0x56]);
}
```
The problem is that `isStaticArray` won't halt when the field is
`byte`.
When I add a `writeln(isStaticArray!(typeof(field)));` it will
write `false` for `mbyte` though...
What's the problem? Is it a bug?
And: Is there a better way to do what I'm trying to do?...
May 19 2017
On 05/19/2017 03:46 PM, Timoses wrote:
foreach (field; fields)
{
// Here it should actually not enter when field is mbyte
(byte)
if (isStaticArray!(typeof(field)))
You probably want `static if` here.
With normal `if`, the body still gets compiled, even if the condition is
compile-time constant false. With `static if`, the body is skipped.
May 19 2017
The easiest way is probably casting:
```
import std.traits;
import std.bitmanip;
class Test {
byte[4] marray;
byte mbyte;
}
void main() {
auto value = [0x12, 0x23, 0x34, 0x45, 0x56];
auto test = cast(Test*) value.ptr;
}
```
May 22 2017
On Tuesday, 23 May 2017 at 06:42:55 UTC, Timoses wrote:
The easiest way is probably casting:
```
import std.traits;
import std.bitmanip;
class Test {
byte[4] marray;
byte mbyte;
}
void main() {
auto value = [0x12, 0x23, 0x34, 0x45, 0x56];
auto test = cast(Test*) value.ptr;
}
```
Don't cast arbitrary types to classes, you're going to stumble
upon very nasty surprises :) I guess you meant struct?
Classes in D are quite fat, and don't start with data members
right away, bookkeeping ClassInfo data comes first.
May 23 2017








Stanislav Blinov <stanislav.blinov gmail.com>