您可能永远不想指定In
,而是推导出来,对吗?
在这种情况下,您需要重载该函数:
template <typename Out, In>
Out f(In x);
template <typename T>
T f(T x);
称它为:
f(42);
f<float>(42);
…但不幸的是,这对于f<int>(42)
. 无论如何,我们可以使用 SFINAE 适当地禁用其中一个重载:
template <
typename Out,
typename In,
typename = typename std::enable_if<not std::is_same<Out, In>::value>::type
>
Out f(In x);
template <typename T>
T f(T x);
为了避免实现中的冗余,让两个函数分派到一个共同的实现,f_impl
.
这是一个工作示例:
template <typename Out, typename In>
Out f_impl(In x) {
std::cout << "f<" << typeid(Out).name() <<
", " << typeid(In).name() <<
">(" << x << ")\n";
return x;
}
template <
typename Out,
typename In,
typename = typename std::enable_if<not std::is_same<Out, In>::value>::type
>
Out f(In x) {
std::cout << "f<Out, In>(x):\t ";
return f_impl<Out, In>(x);
}
template <typename T>
T f(T x) {
std::cout << "f<T>(x):\t ";
return f_impl<T, T>(x);
}
int main() {
f(42);
f<float>(42);
f<int>(42);
}