Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear experts, I have this piece of code:

C++
template <typename genericType = int>
genericType add (genericType a, genericType b)
{
  return a + b;
}

int main ()
{
 int i1 = 1;
 double d2 = 3.14;
 
std::cout << "Add: " << add<> (i1,d2) << std::endl;

return 0;
}

it gives me the following error at compile time:

test.cpp:14:27: error: no matching function for call to 'add'
  std::cout << "Add: " << add<> (i1,d2) << std::endl;
                          ^~~~~
test.cpp:4:13: note: candidate template ignored: deduced conflicting types for parameter 'genericType' ('int' vs. 'double')
genericType add (genericType a, genericType b)
            ^
1 error generated.

Is there a way that I can cast the arguments to be int?
I thought it was possible with the default template value.

Many thanks,
- Mauro.

What I have tried:

C++
template <typename genericType = int>
genericType add (genericType a, genericType b)
{
  return a + b;
}

int main ()
{
 int i1 = 1;
 double d2 = 3.14;
 
std::cout << "Add: " << add<> (i1,d2) << std::endl;

return 0;
}
Posted
Updated 27-Nov-18 1:34am
v2

You have declared the default type to be int so it expects that for both arguments. See Templates (C++)[^] for full explanation.
 
Share this answer
 
Nope, that doesn't work. Since you specified genericType for both a and b then those arguments must have the same type, otherwise template argument deduction fails.
By the way the template default argument has no effect, since the compiler can always deduce genericType type from actual function argument type(s).
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900