使用模板化函数参数的隐式类型转换

Implicit type conversion with templated function parameters

如果我有一个简单的函数需要这样的类型:

class X
{
    public:
        X( int ){}
};

void fx( X  ) {}



fx( 1 ); // implicit converted to X(int); // fine!

如果我对模板类型尝试同样的方法,它不会起作用。

template <typename T>
class Y
{
    public:
        Y( T ){};
};

template <typename T>
void fy( Y<T> );

fy( 2 ); // Y<int> expected, but it fails

有什么技巧可以强制转换吗?

需要隐式执行,直接访问 fy 不是所需要的。我知道我可以通过指定模板参数来强制所有模板 ;)

模板参数推导不考虑任何隐式转换。

您可以手动指定想要的实例化:

fy<int>(2);

在 C++17 中使用模板类型推导,您也可以使用

fy(Y(2));

以及 C++17 之前的版本

fy(Y<int>(2));

template argument deduction不考虑隐式转换;无法推导模板参数 T

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

你可以写一个辅助函数模板。

template <typename T>
void helper(T&& t) {
    fy<std::decay_t<T>>(std::forward<T>(t)); // specify the template argument explicitly
}

然后

helper(2); // T will be deduced as int

参数中不能有隐式转换和模板推导。另一种分解方法:

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

当然,根据 fy,您可以直接将 x 用作 T,并在函数中即时隐式转换。