I wrote a function object template to practice working with templates and included a function template. The function template is, however, causing me trouble.
#include <iostream>
using std::cout;
template <class T> class CArea
{
public:
T operator () (T length, T width)
{
return length*width;
}
};
template <class T> void printArea(T length, T width, CArea<T> area);
int main(void)
{
CArea<int> IntArea;
CArea<double> DoubleArea;
cout << "The area of the int pitch is " << IntArea(15.5, 10) << ".\n";
cout << "The area of the double pitch is " << DoubleArea(15.5, 10) << ".\n";
printArea(12.5, 10, CArea<float>());
cout << "\n";
return 0;
}
template <class T> void printArea(T l, T w, CArea<T> area)
{
cout << "The area of the pitch is " << area(l, w) << ".\n";
return;
}
If I run the code like this I get compiler error:
C2782: template parameter 'T' is ambiguous
I checked the MSDN library and found out I can disambiguate my code by changing the function call in the following way:
printArea<float>(12.5, 10, CArea<float>());
The problem is that I don't fully understand what is going wrong and how it is being fixed. I understand that the compiler cannot determine the parameter type with certainty based on the arguments in the function call. So I specify the parameter type explicitly as if creating an object with a class template? With the third argument (which creates a function object based on the template class), don't I provide a rather unambiguous specification of the parameter type T already?
The compiler is failing to deduce T because your first argument tells it that T is double, your second argument tells it that T is int, and your third argument tells it that T is float. T can't be three types at once!
you could write printArea(12.5, 10.0, CArea<double>());
or printArea(12.5f, 10.f, CArea<float>());
Yes, I see it now and it makes perfect sense. I thought the third argument would be taken to be decisive because I explicitly state the type argument. I now see I only specify the type argument for the class template, so the function template is still left with three possible interpretations of T. Thank you for your quick and lucid response.