Polymorphic copy: Difference between revisions

→‎{{header|Phix}}: added class-based alternative
(Added Wren)
(→‎{{header|Phix}}: added class-based alternative)
Line 1,665:
 
=={{header|Phix}}==
=== traditional object/sequence ===
The object type is the ultimate polymorph - there is <i>nothing</i> that you can store anywhere else that you cannot store in an object.
 
Line 1,699 ⟶ 1,700:
I is a T
I is an S
</pre>
===classes===
{{libheader|Phix/Class}}
Not recommended or formally supported, but these sort of low-level things are perfectly possible.<br>
Note the result from get_struct_fields() is not documented and liable to change between releases.<br>
The deep_copy routine also shows how to break privacy on fetch/set of private fields by faking the context (name).
<lang Phix>include builtins/structs.e
 
function deep_copy(class c)
string name = get_struct_name(c)
class res = new(name)
sequence fields = get_struct_fields(c)
for i=1 to length(fields) do
string field = fields[i][1]
store_field(res,field,fetch_field(c,field,name),name)
end for
return res
end function
 
class T
private atom x
public atom y
procedure show()
printf(1,"This is T%d/%d\n",{x,y})
end procedure
end class
 
T t = new({1,2}),
s = deep_copy(t)
s.y = 3
t.show()
s.show()</lang>
{{out}}
<pre>
This is T1/2
This is T1/3
</pre>
 
7,820

edits