Vio*_*ffe 4 c++ templates template-argument-deduction c++17
这是我想做的:
#include <vector>
template <class ContainerType, typename ComparatorType>
void f(
ContainerType c1,
ComparatorType comp =
[](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;})
{
}
int main()
{
std::vector<int> a{1, 2};
f(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用:could not deduce template argument for 'ComparatorType'。
使用代理函数代替实际的默认参数值是可行的,但似乎过于冗长,有没有更好的方法?更不用说它是不一样的,因为现在我不能在不更改客户端代码中的函数名称的情况下用我自己的默认比较器代替。
#include <vector>
template <class ContainerType, typename ComparatorType>
void f(
ContainerType c1,
ComparatorType comp)
{
}
template <class ContainerType>
void f2(ContainerType c)
{
f(c, [](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;});
}
int main()
{
std::vector<int> a{1, 2};
f2(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
无需更改客户端代码中的函数名称。
您可以重载功能模板。无需使用其他名称。
template <class ContainerType, typename ComparatorType>
void f(
ContainerType c1,
ComparatorType comp)
{
}
template <class ContainerType>
void f(ContainerType c)
{
f(c, [](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;});
}
Run Code Online (Sandbox Code Playgroud)
您不能使默认函数参数有助于模板参数的推导。不允许这样做,因为它在推论过程中会引起一些难以解决的问题。