digitalmars.D.learn - Function return different type according to the parameters.
- nojoking (35/35) Sep 24 2006 How to return different types?For Example:
- Chris Nicholson-Sauls (34/74) Sep 24 2006 Strictly speaking, you can't. There is no overloading on return type. ...
How to return different types?For Example: test.d /++/ import std.stdio; void main() { Test test; test["a"]="A string. "; test["b"]=1234; test["c"]=true; writefln(test["a"],test["b"],test["c"]); } struct Test { char[][char[]] strarr; int[char[]] intarr; bool[char[]] bolarr; void opIndexAssign(int value,char[] key) { intarr[key]=value; } void opIndexAssign(char[] value,char[] key) { strarr[key]=value; } void opIndexAssign(bool value,char[] key) { bolarr[key]=value; } /+??????????????????? opIndex(char[] key) { } ???????????????????+/ }
Sep 24 2006
nojoking wrote:How to return different types?For Example: test.d /++/ import std.stdio; void main() { Test test; test["a"]="A string. "; test["b"]=1234; test["c"]=true; writefln(test["a"],test["b"],test["c"]); } struct Test { char[][char[]] strarr; int[char[]] intarr; bool[char[]] bolarr; void opIndexAssign(int value,char[] key) { intarr[key]=value; } void opIndexAssign(char[] value,char[] key) { strarr[key]=value; } void opIndexAssign(bool value,char[] key) { bolarr[key]=value; } /+??????????????????? opIndex(char[] key) { } ???????????????????+/ }Strictly speaking, you can't. There is no overloading on return type. What you can do, however, is to return a Box (see: std.boxer) or write and return a Var struct, such as this: In which case your opIndex could be something like: -- Chris Nicholson-Sauls
Sep 24 2006