September 24, 2006 Function return different type according to the parameters. | ||||
---|---|---|---|---|
| ||||
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) { } ???????????????????+/ } |
September 24, 2006 Re: Function return different type according to the parameters. | ||||
---|---|---|---|---|
| ||||
Posted in reply to nojoking | 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:
# struct Var {
# static enum Type { Str, Int, Bool }
#
# Type type ;
# union {
# char[] s ;
# int i ;
# bool b ;
# }
# }
In which case your opIndex could be something like:
# Var opIndex (char[] key) {
# Var result ;
#
# if (auto x = key in strarr) {
# result.type = Type.Str ;
# result.s = (*x).dup ;
# }
# else if (auto y = key in intarr) {
# result.type = Type.Int ;
# result.i = *y ;
# }
# else if (auto z = key in bolarr) {
# result.type = Type.Bool ;
# result.b = *z ;
# }
# else {
# throw new Exception("key not found: '" ~ key ~ "'");
# }
# }
-- Chris Nicholson-Sauls
|
Copyright © 1999-2021 by the D Language Foundation