Thread overview | |||||
---|---|---|---|---|---|
|
November 29, 2016 how to copy const struct with indirections to mutable one (of the same type) | ||||
---|---|---|---|---|
| ||||
I had the following code: ``` import std.algorithm: equal; struct Data { int[3] arr; } int main() { auto const_data = const(Data)([1, 2, 3]); assert(const_data.arr[].equal([1, 2, 3])); Data mutable_data = const_data; assert(mutable_data.arr[].equal([1, 2, 3])); return 0; } ``` It workred fine. Now I replace static array by std.container.Array: ``` import std.algorithm: copy, equal; import std.container: Array; struct Data { Array!int arr; this(R)(R r) { r.copy(arr[]); } ref Data opAssign(const(Data) other) { pragma(msg, __FUNCTION__); import std.range: lockstep; this.arr.length = other.arr.length; foreach(ref s, ref d; lockstep(other.arr[], this.arr[])) d = s; return this; } } int main() { auto const_data = const(Data)([1, 2, 3]); assert(const_data.arr[].equal([1, 2, 3])); Data mutable_data = const_data; assert(mutable_data.arr[].equal([1, 2, 3])); return 0; } ``` and it fails now because: `` Error: conversion error from const(Data) to Data ``` I can solve my problem in other ways but I'd like to know why opAssign overload doesn't work in this case? Thank in advance |
November 29, 2016 Re: how to copy const struct with indirections to mutable one (of the same type) | ||||
---|---|---|---|---|
| ||||
Posted in reply to drug | On Tuesday, 29 November 2016 at 10:46:04 UTC, drug wrote:
> I had the following code:
> ```
> import std.algorithm: equal;
>
> [...]
You are not calling the (identity) opAssign here, but postblit.
To call identity opAssign, you need an already constructed instance:
```
Data mutable_data;
mutable_data = const_data;
```
|
November 29, 2016 Re: how to copy const struct with indirections to mutable one (of the same type) | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mathias Lang | 29.11.2016 13:49, Mathias Lang пишет:
> On Tuesday, 29 November 2016 at 10:46:04 UTC, drug wrote:
>> I had the following code:
>> ```
>> import std.algorithm: equal;
>>
>> [...]
>
> You are not calling the (identity) opAssign here, but postblit.
>
> To call identity opAssign, you need an already constructed instance:
>
> ```
> Data mutable_data;
> mutable_data = const_data;
> ```
Thanks for clarification!
|
Copyright © 1999-2021 by the D Language Foundation