Re: User defined conversion to builtin type gives l-value?
Alf P. Steinbach schrieb:
* Arne Mertz:
Hi all, following example:
template <class T, class U>
T foo(U const& u, T const& t)
{
return T temp(u) /= t;
This is syntactically incorrect.
Perhaps you meant
return T(u)/t;
Yes, sorry.
}
gives me an error "'/=' left operand has to be an l-value" on MSVC
2008 express, if T is a builtin type (e.g. double). In my case, U has
an konversion operator to double. If I try the same with T being a
builtin class
There are only a few classes that have direct compiler support, they
include typeinfo and some exception classes.
And it's still arguable whether they could be referred to as builtin
classes.
Probably you meant "builtin type".
Nope, sorry, I meant user defined class.
and either providing a konversion ctor for T or providing an
konversion operator for U, it works.
My question is: is that right according to the standard?
Your code should not compile, if that's what you're asking.
I found a line saying that implicit standard conversions result in
l-values, but as far as i can see this is an explicitly called user
defined conversion or not?
Huh?
Okay, seems I messed it all up a bit. So another try here:
template <class T, class U>
T foo(U const& u, T const& t)
{
return T(u) /= t;
}
class X {};
struct Y
{
Y() {};
Y(X const&) {}; //konversion ctor userdefined->userdefined (1)
Y(int); //konversion ctor builtin->userdefined (2)
Y& operator /= (Y const& rhs) {}
};
struct Z
{
operator Y() const; //konversion op userdefined->userdefined (3)
operator double() const; //konversion op userdefined->builtin (4)
};
int main()
{
X x; Y y; Z z; int i; double d;
foo(x, y); // calls (1), ok.
foo(i, y); // calls (2), ok.
foo(z, y); // calls (3), ok.
foo(z, i); // calls (4), ERROR, because int(z) is l-value
foo(i, d); // calls double(i) /= d; ERROR because double(i) is
l-value
}
as far as I can the conversion in foo is explicit. I could not find
any phrase in the standard saying whether the result of an explicit
conversion is an l-value or an r-value. as it seems, either the
conversion to userdefined types gives l-values, or the userdefined
op/= can be applied to r-values in contrast to the builtin op/=
Which is the case?
greets
A