Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type conversion with templated function parameters

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 ;)

like image 930
Klaus Avatar asked Oct 20 '25 04:10

Klaus


1 Answers

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
like image 171
songyuanyao Avatar answered Oct 22 '25 19:10

songyuanyao