www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How does one cast to an array type?

reply Vinay Sajip <vinay_sajip yahoo.co.uk> writes:
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
Oct 17 2019
next sibling parent Andrea Fontana <nospam example.com> writes:
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
Oct 17 2019
prev sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
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.
Oct 17 2019
parent Vinay Sajip <vinay_sajip yahoo.co.uk> writes:
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
Oct 17 2019