Magic type return

Philippe Sigaud philippe.sigaud at gmail.com
Wed Jul 18 07:42:15 PDT 2012


> class Known
> {
>          void* data; // external data by c api
>          int type;  // 0 for int, 1 for string, etc. ..
> }
>
> How can I implement a method like this?
>
> Known  known;  // <-- suppose known.type == 1;
> string s  = known.value(); // <-- automatic
>
> I just know how to do this:
>
> string s = know.value!string();

As bearophile said, you cannot change a value's type (which is a
compile-time construct) with a runtime value, as is Known.type.

Second point, in D, the rhs is fully evaluated before being assigned to the
lhs, I think. So, known.value() must evaluate to *something*, without
knowing it will be assigned to a string.
In your example, what happens if known.type != 1?

You can use Phobos Variant, (or Algebraic if the range of types you plan to
use is known beforehand). Then, you should test typeid before using it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20120718/0689ce58/attachment.html>


More information about the Digitalmars-d-learn mailing list