Reputation: 185
Given the following templated method
template <typename T>
T max(T x, T y)
{
return (x > y)? x : y;
}
I want the following call to work:
int main()
{
cout << max(3, 7.0) << std::endl; //compiler error
}
I understand that the compiler fails due to the fact that I'm passing 2 different datatypes while my template only accepts 2 parameters with same type. The easiest solution would be using polymorphism and creating a new template method that uses type T and X instead of 2 types T but I want to ask you if there's a way to make some sort of cast of parameter y to the type of parameter x without modifying the call in main()
Upvotes: 1
Views: 519
Reputation: 22152
It is not exactly clear from your question what type you expect T
to be in this scenario, but if you want it to be e.g. the type of the first argument, then you can make the second parameter a non-deduced context:
template <typename T>
T max(T x, std::type_identity<T>::type y)
{
return (x > y)? x : y;
}
std::type_identity
is a C++20 feature but its implementation is really simple:
template<typename T>
struct type_identity {
using type = T;
};
Everything left of the scope resolution operator in the parameter is non-deduced, so the whole parameter is non-deduced context and will not participate in template argument deduction. Instead normal implicit conversions will be applied in overload resolution.
Upvotes: 1
Reputation: 5095
Yes, you can do that by creating another template method:
template<class T, class U>
T max(T x, U y) {
return max(x, static_cast<T>(y));
}
Note: If it's just about max, use std::max
from the STL.
Upvotes: 0
Reputation: 87
that fails because of template's type deduction which fails to deduce between int
and double
, you could either explicitly specify the template type, use two template parameters or cast it inside to T
with static_cast
Upvotes: 1