If I have a simple function expecting a type like:
class X
{
public:
X( int ){}
};
void fx( X ) {}
fx( 1 ); // implicit converted to X(int); // fine!
If I try the same for templated types, it will not work.
template <typename T>
class Y
{
public:
Y( T ){};
};
template <typename T>
void fy( Y<T> );
fy( 2 ); // Y<int> expected, but it fails
Is there any trick to force the conversion?
It is needed to do it implicit, a direct access on fy is not what is wanted. I know that I can force all templates with specifying the template parameters ;)
Implicit conversions won't be considered in template argument deduction; the template parameter T just can't be deduced.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
You can write a helper function template.
template <typename T>
void helper(T&& t) {
fy<std::decay_t<T>>(std::forward<T>(t)); // specify the template argument explicitly
}
then
helper(2); // T will be deduced as int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With