I have a function :
template<class T>
static string
format(T ui, T sentinal, char listSeparator)
{
stringstream s;
if (ui == sentinal)
{
s << "n/a" << listSeparator;
}
else
{
s << ui << listSeparator;
}
return s.str();
}
The way the function was called is :
output << format(field1,Backend::NA_Value, csvSeparator);
output << format(field2,Backend::NA_Value, csvSeparator);
/// ...etc
Previously field1 and field2 were of the type unsigned int .
It was decided to change these types to be unsigned long long.
But the compilation error occurs :
std::string format(T,T,char)' : template parameter 'T' is ambiguous
main.cpp(39) : see declaration of 'format'
could be 'Juint'
'unsigned __int64'
What is the reason for that?NA_Value?It is defined as :
static const Juint NA_Value = (Juint) -1;
typedef unsigned int Juint
It can`t determine the template T ?!
Where from compiler decides about __int64?
This is a problem of template type deduction, where you have the same type occurring multiple times in the signature of a function. The compiler just doesn’t know which of the two types you want
Tto be, because in the call the two occurrences are of a different type.You call
formatlike the following (withJuintbeing replaced according to yourtypedef):You changed the type of the former argument so now it is different from the second. Before you did this change, both parameters had the same type.
To solve the problem, you have the following options:
Make the template types different. (see answer by Joachim Pileborg)
Force a specific type by explicitly stating it as a template parameter when you call the function. This will automatically cast the non-matching parameter(s) like you are used to it for normal functions (no type deduction happens in this case):
Cast one of the parameters to the other type. This makes both parameters be the same and type deduction will succeed:
Change the typedef of
Juint, too, so the types become the same again and type deduction also succeeds.Add type traits /
enable_ifwhich will restrict the template types to specific classes of types fulfilling a condition, but in your case I don’t think that this is what you want.Personally, I’d wish there was another option: It would be nice to have the type deduction only perform on the first parameter and force the second parameter to be cast on the call site automatically (like a “
Tbut don’t deduce” parameter type). But there isn’t such an option.The best options in your case is to make
Juintalso of the same type (4th option on the list) or to make your function “more general” by going for the first option. Care has to be taken on the usages of the types within the function, as pointed out in the answer by Joachim Pileborg in general, but in your case it should be fine without changing the function’s body.