模板类型推导,即使是空列表

template type deduction even with empty list

我在 cppreference 上读到:

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.

以下示例:

std::tuple t1(1, 2, 3);              // OK: deduction
std::tuple<int,int,int> t2(1, 2, 3); // OK: all arguments are provided
std::tuple<int> t4(1, 2, 3);         // Error

到目前为止,我的理解是:

所以在我下面的例子中:

template<typename T1, typename T2>
auto max(T1 a, T2 b) -> typename std::decay<decltype(true? a:b)>::type
{
   return  b < a ? a : b;
}

auto c = ::max('c', 7.2); //<<< Works as template deduction took place
auto d = ::max<int>('c', 7.2);  //<<<< WOrks !!! Why

那么对于最后一行,为什么即使我只提供了一个模板列表 (T1) 而不是两者,它仍然有效?我期待错误!!

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place

这是关于 类 的推导指南,这是一个新的 C++17 特性。

在C++17之前也是一个错误

std::tuple t1(1, 2, 3);

因为在 C++17 之前,类.

的显式 all 模板参数是必需的

So in my example below :

你的例子是关于模板函数的推导。

完全不同的东西。

对于函数,您也可以显式显示一些模板参数,不一定是所有模板参数。