www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Why not allow object to object conversion via `std.conv.to`?

reply Andrej Mitrovic <none none.none> writes:
This might be a silly question, but I'd like to know if `to` can be expanded in
its functionality. I'm not talking about converting base and derived, but two
separate classes which appear unrelated but where the library writer knows how
to convert from one type to another. A superficial example of what I'd like to
work with:

import std.conv;
void main()
    auto bar = new Bar();
    auto foo = new Foo();
    foo = to!Foo(bar);

class Foo

class Bar
    Foo to(Foo)()
        return new Foo();

Fails at runtime with: std.conv.ConvException std\conv.d(37): Cannot convert
object of static type toConversion.Bar and dynamic type toConversion.Bar to
type toConversion.Foo

Of course ultimately I'd write `to` with template constraints instead of
hardcoding the Foo type there.

I see `to` as a really cool way of converting between values of different
types, and I use it all the time when its possible. But I think its
functionality should be expanded for this case.

What I'm noticing is that library writers, especially those who wrap existing
C/C++ libraries, create conversion functions with arbitrary names for some
class/struct, e.g. a method called "toNativeString". 
In other cases, they create a constructor taking a type from which to convert
to, and then return the new object of its own type. 

Here's a superficial example:

string makeMeGreat;
SuperString foo = new SuperString();
// more code..
foo = new SuperString(makeMeGreat);  // constructor call
string bar = foo.toNativeString();  // specially named method

But if SuperString was allowed to have a templated `to` method function, and if
std.conv.to could somehow use it, the last two lines become:

foo = to!SuperString(makeMeGreat);
string bar = to!string(foo);

Is this even remotely possible to implement?

If I'm completely misunderstanding the point of `to`, just let me know and I'll
be on my way. But `to` is just great to have and I use it whenever I can.
Mar 16 2011
parent simendsjo <simen.endsjo pandavre.com> writes:
One issue with this is that an object needs to know about every object
it can convert to.

Perhaps a better solution is to create something like AutoMapper[1]
for D

[1] http://automapper.codeplex.com/
Mar 17 2011