Thread overview | ||||||
---|---|---|---|---|---|---|
|
October 17, 2019 How does one cast to an array type? | ||||
---|---|---|---|---|
| ||||
Are arrays and objects part of a unified type system? Specifically, if I do void foo(Object x) { if (typeid(x) == typeid(Object[])) { auto a = cast(Object[]) x; } } I get a compilation error: onlineapp.d(3): Error: cannot cast expression x of type object.Object to Object[] What's the way to achieve the cast, which should be safe given the typeid check? Thanks and regards, Vinay Sajip |
October 17, 2019 Re: How does one cast to an array type? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Vinay Sajip | On Thursday, 17 October 2019 at 12:19:03 UTC, Vinay Sajip wrote: > Are arrays and objects part of a unified type system? Specifically, if I do > > void foo(Object x) { > if (typeid(x) == typeid(Object[])) { > auto a = cast(Object[]) x; > } > } > > I get a compilation error: > > onlineapp.d(3): Error: cannot cast expression x of type object.Object to Object[] > > What's the way to achieve the cast, which should be safe given the typeid check? > > Thanks and regards, > > Vinay Sajip Did you try templates? It seems easier: https://run.dlang.io/is/BbkTCw Andrea |
October 17, 2019 Re: How does one cast to an array type? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Vinay Sajip | On Thursday, 17 October 2019 at 12:19:03 UTC, Vinay Sajip wrote:
> Are arrays and objects part of a unified type system?
No, they are separate. You can define a class that contains an array, but it doesn't work like that automatically.
You'll want to use a wrapper class or a variant type or a template or something for this depending on your exact use case.
|
October 17, 2019 Re: How does one cast to an array type? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Thursday, 17 October 2019 at 12:40:33 UTC, Adam D. Ruppe wrote:
> On Thursday, 17 October 2019 at 12:19:03 UTC, Vinay Sajip wrote:
>> Are arrays and objects part of a unified type system?
>
> No, they are separate. You can define a class that contains an array, but it doesn't work like that automatically.
>
> You'll want to use a wrapper class or a variant type or a template or something for this depending on your exact use case.
The use case is that I have a specialised comparator function that takes any two objects, including potentially array of objects, and processes things accordingly. Perhaps a Variant will be the best bet, as the decision as to how to process has to be made at run time rather than compile time, and effectively based on user inputs.
Thanks for the suggestions,
Vinay Sajip
|
Copyright © 1999-2021 by the D Language Foundation