是否可以在调用函数模板时只指定一些模板参数,让编译器推导其他的

Is it possible to specify only some template parameters when calling a function template and let the compiler deduce the others

考虑以下函数模板:

template <typename T1, typename T2>
void foo(T1 a, T2 b){// Do something.}

现在假设我希望 T1int,但编译器根据 b 的类型推导出 T2。类似于 foo<int,...>(1,b)。可能吗?

谢谢!

是的!

foo<int>(1, b);

但是在上面的例子中没有任何好处。如果您的第一个参数尚未推导为 int:

,则差异是可见的
foo<int>(3.2f, b);
//       ^^^^ Implicit conversion

昆汀的回答最方便。

但是还有其他方法可以解决这个问题。由于强制特定模板类型会导致静默转换,有时只进行显式转换可能更明智。

double x = 1.1;
foo(static_cast<int>(x), boost::lexical_cast<int>(y));

经典示例是 std::move 的使用,它仅转换为 xvalue。