How to use interface template? How to model interface template properly in D.
Matthew Ong
ongbp at yahoo.com
Thu May 26 22:55:49 PDT 2011
Hi All,
The main aim here is to find out how to model similar syntax within D.
Due to the nature of the architecture of the library that I have
designed in Java and heavily leans towards interface generics.
It works well with java.
Yes. I am aware about Tuple to allow me to do multiple value return.
The point is Not about returning multiple, but how to moduel
public interface DefType1<T1> { // Please note this is like interface
template
public Throwable getError();
public T1 getValue();
public String getDesc();
}
// Elsewhere.
public class RetVal1<T1> implements DefType1<T1> {
private RetVal1() {
}
public static <T1> RetVal1<T1> make(T1 value) {
RetVal1<T1> obj = new RetVal1<T1>();
obj.mValue = value;
return obj;
}
private Throwable mError;
public void setError(Throwable error) {
mError = error;
}
public Throwable getError() {
return mError;
}
private T1 mValue;
public T1 getValue() {
return mValue;
}
private String mDesc;
public String getDesc() {
return mDesc;
}
}
// Yet, else where
class Account{...}
public static RetVal1<Account> methodA(int num, String str) { //
similar to Instantiation template
... // do something.
return RetVal2.<Account>make(num, str);
}
void main(string[] args){
RetVal1<Account> ret = methodA(1, "abc"); // some method call that return
if(ret.getError()==null){
Account acc=ret.getValue1();
prnln("amount=" + acc.getAmount());
}
}
http://www.digitalmars.com/d/2.0/template.html#Constraint
Struct, Union, and Interface Templates
...
Analogously to class templates, struct, union and interfaces can be
transformed into templates by supplying a template parameter list.
However there is no example shown.
In D the syntax should more or less look similar:
interface DefType1(T1) { // No issue here
public:
Throwable getError();
T1 getValue();
String getDesc();
}
public class RetVal1(T1) : DefType1(T1) { // ### or IS IT: DefType1!(T1) ??
...
public static RetVal1(T1) make(T1)(T1 value) { // static method template
RetVal1(T1) obj = new RetVal1(T1)(); // ### or IS IT: new
RetVal1!(T1)();
obj.mValue = value;
return obj;
}
...
}
public static RetVal1(Account) methodA(int num, String str) { //### How
to do that?? Compilation error.
Account acc=new Account();
... // do something.
return RetVal2.(Account)make(ac); //### How to do that?? compilation
error also
}
RetVal1(Account) ret = methodA(1, "abc"); // Compilation error also.
if(ret.getError()==null){
Account acc=ret.getValue1();
prnln("amount=" + acc.getAmount());
}
------------------------------------------------------------------------
Kindly show some compilable and working code sample.
Thanks very much.
--
Matthew Ong
email: ongbp at yahoo.com
More information about the Digitalmars-d-learn
mailing list