Klaus
Klaus

Reputation: 25613

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

Upvotes: 4

Views: 2137

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

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

Upvotes: 4

kabanus
kabanus

Reputation: 25895

You cannot have implicit conversion and template deduction in the argument. Another way to break it up:

template <typename T>
void fy( T x ) {
    Y<T> y = x;
    //Use y
    return;
}

Of course, depending on fy you may be able to use x directly as T, and convert implicitly on the fly in the function.

Upvotes: 3

lubgr
lubgr

Reputation: 38277

Template argument deduction does not take any implicit conversions into account.

You can manually specify the desired instantiation:

fy<int>(2);

Using template type deduction with C++17, you can also go with

fy(Y(2));

and with pre-C++17

fy(Y<int>(2));

Upvotes: 1

Related Questions