返回动态类型
我知道类似的模板
T add(T)(T a, Tb){
return a + b;
}
,但这需要用户询问将返回哪种类型,我想在方法内部计算将返回哪种类型,例如:
T getField( size_t column ){
if( column == 0 )
T = int;
else
T = string;
return to!T("1");
}
我不知道是否可以转换为对象并更改原型。
感谢大家
i know template like
T add(T)(T a, Tb){
return a + b;
}
But this need to user ask which type will be return, me i want compute inside method which type will be returned like:
T getField( size_t column ){
if( column == 0 )
T = int;
else
T = string;
return to!T("1");
}
i do not know if i can cast to object and change prototype.
Thanks to all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
D 与 C、C++、C# 和 Java 一样,都是静态类型语言。 所有类型都必须在编译时已知。所以,不,你不能做你想做的事。
现在,您可以使用继承,联合,或 std.variant.Variant 以获得动态类型的形式,但与您想要做的不太一样。这只适用于动态语言。
对于类,类引用可以指向派生类的实例,而不是引用所针对的基类,因此您可以获得多态/动态行为,但基类的类型在编译时是已知的,并且引用引用的任何内容都必须是派生类型,因此必须是类。
使用联合,您可以拥有一个变量,该变量可以使用相同的内存保存不同类型(因此它一次只能是一种类型),但它通常被认为是相当低级的构造,如果您不这样做,最好避免真的不需要它。联合不会跟踪其当前类型,因此如果它既可以是
int
又可以是string
,那么它很容易持有>int
,但您将其用作字符串
(反之亦然),从而导致严重的错误。使用
Variant
(这可能是您想要使用的),您可以拥有一个可以保存不同类型的变量 - 类似于联合 - 但您不指定它可以保存哪些类型hold(与联合不同),并且它实际上会跟踪它当前持有的类型(与联合不同),因此使用起来更安全。D, like C, C++, C#, and Java is a statically typed language. All types must be known at compile time. So, no, you can't do what you're trying to do.
Now, you could use inheritance, unions, or std.variant.Variant to get a form of dynamic typing, but not quite like what you're trying to do. That only works in dynamic languages.
With classes, a class reference can point to an instance of a derived class rather than the base class that the reference is for, so you can get polymorphic/dynamic behavior, but the type of the base class is known at compile time, and anything that the reference refers to must be a derived type and therefore must be a class.
With unions, you can have one variable which can hold different types using the same memory (so it can only be one type at a time), but it's generally considered a fairly low-level construct and best avoided if you don't really need it. A union does not keep track of what its current type is, so if it could be both an
int
and astring
, it's quite easy for it to be holding anint
, but you use it as astring
(or vice versa), causing nasty bugs.With
Variant
(which is probably what you want to use), you can have one variable which can hold different types - similar to a union - but you don't specify which types that it can hold (unlike a union), and it actually keeps track of what type it currently holds (unlike a union), so it's much safer to use.