Re: Templated cast operator
Victor Bazarov wrote:
uvts_cvs@yahoo.com wrote:
Hi everybody, do you think the next little chunk of code has
to compile?
struct foo
{
template <typename T> operator T() const {return T();}
};
int main()
{
return 1 + foo();
}
I thought that it has to compile because we can cast the foo
object to int and pass it to operator +, but some compilers
seem not to agree with me (but some others do!). What do you
think? Does it adhere to the ISO standard?
Isn't it also true that we can just as well cast a 'foo'
object to 'long' or 'char' or 'double'? So, how (on what
basis) should the compiler pick 'int' here?
In the case of overloading, the compiler assimilates the
built-in operators to set of overloaded functions. In the case
of +, functions which take 2 parameters. It then chooses the
one function which is 1) a better match than any other for at
least one argument, and 2) no worse match for any other
argument. In this case, operator+(int,int) is the best match
argument 1, and all possible functions are equal matches for
argument 2 (so operator+(int,int) is not a worse match).
Thus, I think that this is legal. The only possible ambiguity
would be between foo::operator T<int>() and foo::operator
T<const int>(). (CV qualification conversions rank as an exact
match.) But these are two instantiations of the same function
template, and the rules say that template argument deduction
will only find a single instantiation for each function
template.
--
James Kanze GABI Software
Conseils en informatique orient9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S9mard, 78210 St.-Cyr-l'cole, France, +33 (0)1 30 23 00 34
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]