On Nov 17, 6:33 pm, mathieu <mathieu.malate...@gmail.comwrote:
Could someone please tell me what is wrong with the following
-ugly- piece of c++ code. Why when I explicititely set the
template parameter my gcc compiler start getting confused:
bla.cxx: In function 'int main()':
bla.cxx:25: error: call of overloaded 'foo(short unsigned int*&)' is
ambiguous
bla.cxx:2: note: candidates are: void foo(OutputType*) [with PixelType
= short unsigned int, OutputType = short unsigned int]
bla.cxx:10: note: void foo(PixelType*) [with PixelType
= short unsigned int]
The compiler isn't confused; it's just doing what the standard
requires:-).
with code:
template <class PixelType,class OutputType>
void foo(OutputType *outputCurve)
{
PixelType pt;
}
template <class PixelType>
void foo(PixelType *outputCurve)
{
foo<PixelType,PixelType>(outputCurve);
}
int main()
{
unsigned short *o = 0;
// foo(o); // ok
foo<unsigned short>(o); // not ok
return 0;
}
OK. You have two function templates named foo, which will be
considered each time you invoke a function named foo; overload
resolution will determine which one is chosen. Strictly
speaking, function overload chooses between functions, not
between function templates; when you call a function for which
there are function templates, the compiler tries to deduce the
template arguments for each function template, and if it
succeeds, it adds the instantation (the instantiation of a
function template is a function) to the overload set.
In the first case, foo(o), template argument deduction fails for
the first function template; the compiler cannot deduce the type
of PixelType, so no function is added. It succeeds for the
second, with unsigned short for PixelType, the the function
foo<unsigned short>( unsigned short* ) is added to the overload
set. Since the overload set only contains a single function,
there is no ambiguity.
In the second case, where you call foo<unsigned short>, the
procedure is exactly the same. Except that argument deduction
works for both of the functions; for the first, it gives an
instantiation of foo<unsigned short, unsigned short>, and for
the second, an instantiation of foo<unsigned short>. (For the
second, there's really not much to deduce in the usual sense of
the word, but formally, deduction takes place, and the results
are added to the overload set.) The result is that you end up
with two functions with the same parameter, which results in an
ambiguity from overload resolution.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34