On Thursday, 12 December 2013 at 14:47:17 UTC, Joseph Rushton
Wakeling wrote:
On 12/12/13 10:15, Simen Kjærås wrote:
Simply put, implicit conversions are not bad, nor good. They
are exactly what
you use them for.
Conversely, sometimes you want to be able to say, absolutely
explicitly, "This function _must_ receive input of _this exact
type_ with no implicit conversion allowed even if it normally
would be."
You can write something like:
void acceptMyType(T)(T arg) if(is(T == MyType))
{
...
}
Yes, this way is complex, but this situation is rare and we
can put up with it.
IMO, implicit conversion possibility for user types should be in
a language, but this possibility should seems unattractive for
user. User should know that he can use this ability only if he
sure that he want it.
May be opImplicitCastFrom method is a good solution, but it
should be a static method whick accept T arg and returns UserType
object.
struct UserType
{
int a;
static UserType opImplicitCastFrom(int a){return
UserType(x);}
}
UserType o = 5; //should be converted to UserType o =
UserType.opImplicitCastFrom(5);
implicit calling of constructor should be deprecated in this case.
UserType o2 = UserType (5); //use constructor
void foo(UserType x);
foo(5); // => foo(UserType.opImplicitCastFrom(5));
opImplicitCastFrom shouldn't be a non-static method (like
opAssign), because we would need to call default constructor
before opImplicitCastFrom call in this case, and if class doesn't
define default constructor we wouldn't able to provide implicit
conversion.
Another suggestion: add special form of alias this construction:
struct UserType
{
int a;
alias myImplicitCast this;
static UserType myImplicitCast(int a){return UserType(x);}
}
If alias this argument is a static function which accepts one
parameter and returns typeof(this), it can be used for implicit
conversion.