判断一个类型是否为 Nullable 并获取基类型?
Determine if a type is Nullable and get the base type?
假设我有这个函数模板:
void bar(T)(T obj) {
// ...
}
如果 T
是 Nullable!U
,我想更改函数的行为,因此如果 obj.isNull
是 true
,我会做一些替代流程,或者以其他方式继续,就好像传递了普通 U
类型一样。
void bar(T)(T obj) {
static if(is(T == Nullable!U)) { // ?
if(obj.isNull) {
writeln("Object was null!");
return;
}
auto realObj = obj.get;
} else {
alias realObj = obj;
}
writeln("Object was "~to!string(realObj));
}
有没有办法检查 T
是否是 Nullable
的实例,如果是,获取包装类型?
或者更一般地说,有没有办法检查类型 T
是否是某个模板 Foo
的实例化,如果是,则获取模板参数?
您可以为 Nullable
提供特定的重载:
void bar(T : Nullable!U, U)(T obj) {
if (obj.isNull) {
writeln("Object was null!");
return;
}
bar(obj.get);
}
void bar(T)(T obj) {
writeln("Object was "~to!string(obj));
}
你的代码大部分是正确的,你只需要改变这一行:
static if(is(T == Nullable!U))
至此
static if(is(T == Nullable!U, U))
和 U
将别名为 Nullable
的类型(即 int
,...)
假设我有这个函数模板:
void bar(T)(T obj) {
// ...
}
如果 T
是 Nullable!U
,我想更改函数的行为,因此如果 obj.isNull
是 true
,我会做一些替代流程,或者以其他方式继续,就好像传递了普通 U
类型一样。
void bar(T)(T obj) {
static if(is(T == Nullable!U)) { // ?
if(obj.isNull) {
writeln("Object was null!");
return;
}
auto realObj = obj.get;
} else {
alias realObj = obj;
}
writeln("Object was "~to!string(realObj));
}
有没有办法检查 T
是否是 Nullable
的实例,如果是,获取包装类型?
或者更一般地说,有没有办法检查类型 T
是否是某个模板 Foo
的实例化,如果是,则获取模板参数?
您可以为 Nullable
提供特定的重载:
void bar(T : Nullable!U, U)(T obj) {
if (obj.isNull) {
writeln("Object was null!");
return;
}
bar(obj.get);
}
void bar(T)(T obj) {
writeln("Object was "~to!string(obj));
}
你的代码大部分是正确的,你只需要改变这一行:
static if(is(T == Nullable!U))
至此
static if(is(T == Nullable!U, U))
和 U
将别名为 Nullable
的类型(即 int
,...)