www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Function return different type according to the parameters.

reply nojoking <kuangdong gmail.com> writes:
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
parent Chris Nicholson-Sauls <ibisbasenji gmail.com> writes:
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