www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - null as parametr

reply AntonSotov <nepuvive rainmail.biz> writes:
import std.stdio;

void myFunc(T)(in T val) {
     static if(is(T == string)) {
         writeln("string: ", val);
     }
     static if(is(T : long)) {
         writeln("long: ", val);
     }
     static if                         // WHAT HERE ?
         writeln("null");
     }
}

int main(string[] args)
{
     myFunc("abc");
     myFunc(123);
     myFunc(null);
     return 0;
}
//--------------------------------------------------
How to transfer <null> as parameter type?
Jul 30 2016
parent reply Seb <seb wilzba.ch> writes:
On Sunday, 31 July 2016 at 05:22:40 UTC, AntonSotov wrote:
 import std.stdio;

 void myFunc(T)(in T val) {
     static if(is(T == string)) {
         writeln("string: ", val);
     }
     static if(is(T : long)) {
         writeln("long: ", val);
     }
     static if                         // WHAT HERE ?
         writeln("null");
     }
 }

 int main(string[] args)
 {
     myFunc("abc");
     myFunc(123);
     myFunc(null);
     return 0;
 }
 //--------------------------------------------------
 How to transfer <null> as parameter type?
just have a look with pragma(msg, T) what the compiler is inferring ;-) -> typeof(null) seems to be a Voldemord type that can't be expressed directly, hence you can do: static if(is(T : typeof(null))) { writeln("null"); } ... but does this really help you? A string can be null too, so whatever you do you most likely should check that with `val is null` too.
Jul 30 2016
parent reply AntonSotov <nepuvive rainmail.biz> writes:
2 Seb

Thank you!
is (T: typeof (null)) - very comfortable
Jul 30 2016
parent Andrew Godfrey <X y.com> writes:
On Sunday, 31 July 2016 at 05:41:55 UTC, AntonSotov wrote:
 2 Seb

 Thank you!
 is (T: typeof (null)) - very comfortable
An example of Seb's warning: What happens if you have: string s = null; MyFunc(s); I'm guessing it doesn't do what you want. But it isn't clear what you want - null is a value, not a type. It's just as if you were saying: is (T: typeof (-3))
Jul 31 2016