Yes I did it using Variant and it works fine Il giorno mer, 18/07/2012 alle 16.42 +0200, Philippe Sigaud ha scritto:
> > 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. >