Question

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

Was it helpful?

Solution

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 a string, it's quite easy for it to be holding an int, but you use it as a string (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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top