简体   繁体   English

具有模板化函数参数的隐式类型转换

[英]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. 要做到这一点隐含这是需要的,在FY直接访问是不是被通缉。 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. 模板参数T不能被推导。

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

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. 当然,根据fy您也许可以直接将x用作T ,并在函数中进行隐式转换。

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 在C ++ 17中使用模板类型推导,您还可以

fy(Y(2));

and with pre-C++17 以及C ++ 17之前的版本

fy(Y<int>(2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM