www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - implicit casting from primitive type

reply Mariusz =?UTF-8?B?R2xpd2nFhHNraQ==?= <alienballance gmail.com> writes:
Hello,
this will be easy question. I defined attributes, that are taking my custom 
structures as attributes. Then, I'd like to add implicit conversion to this 
structures from primitive types, such as:
<code>
some.attribute = [1, 2, 3];   // i'd like to do that
some.attribute = MyStruct(1, 2, 3); // now it's like that
</code>
opCast can be used only to casting FROM my type, but not TO...
Was that in a book?

Thanks,
Mariusz Gliwiński
Aug 29 2011
parent reply Ali =?iso-8859-1?q?=C7ehreli?= <acehreli yahoo.com> writes:
On Mon, 29 Aug 2011 21:33:13 +0200, Mariusz Gliwiński wrote:

 Hello,
 this will be easy question. I defined attributes, that are taking my
 custom structures as attributes. Then, I'd like to add implicit
 conversion to this structures from primitive types, such as: <code>
 some.attribute = [1, 2, 3];   // i'd like to do that some.attribute =
 MyStruct(1, 2, 3); // now it's like that </code>
 opCast can be used only to casting FROM my type, but not TO... Was that
 in a book?
 
 Thanks,
 Mariusz Gliwiński

To solve it for this specific case, you can overload attribute() to take int[]: import std.exception; struct MyStruct { int i; int j; int k; } struct CustomStruct { MyStruct ms; property void attribute(int[] args) { enforce(args.length == 3); ms = MyStruct(args[0], args[1], args[2]); } } void main() { auto some = CustomStruct(); some.attribute = [ 1, 2, 3 ]; } Ali
Aug 29 2011
parent Mariusz =?UTF-8?B?R2xpd2nFhHNraQ==?= <alienballance gmail.com> writes:
Ali Çehreli wrote:
 To solve it for this specific case, you can overload attribute() to take
 int[]:

I know, but i don't really want to. Too many overrides or templates, but i'll consider it if wont find any better solution. Thanks, Mariusz Gliwiński
Aug 29 2011