根据模板参数的默认值启用模板参数类型的自动扣除
Enabling automatic deduction of template argument type based on that argument's default value
这就是我想做的:
#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;
}
但它不起作用: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;
}
无需更改客户端代码中的函数名称。
您可以很好地重载函数模板。无需使用其他名称。
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;});
}
不能使默认函数参数参与模板参数推导。这是不允许的,因为它在扣除过程中提出了一些难以解决的问题。
在考虑默认参数之前执行模板推导。此外,lambda 不允许出现在未计算的操作数中。
您可以先将默认函数分配给变量。然后你可以拼出它的类型。例如:
auto default_functor = [](int x){ return x > 0; };
template <typename T, typename F = decltype(default_functor)>
auto function(T x, F f = default_functor)
{
return f(x);
}
现在您可以像往常一样使用该函数:
bool even(int x)
{
return x % 2 == 0;
}
struct Odd {
bool operator()(int x) const
{
return x % 2 == 1;
}
};
void g()
{
function(1); // use default functor
function(1, even); // use a free function
function(1, Odd{}); // use a function object
function(1, [](int x){ return x < 0; }); // use another lambda
}
无需显式指定类型。
注意:根据@StoryTeller,如果您在标头中使用它,这可能会导致 ODR 违规。在这种情况下,您可以使用命名函子类型:
struct Positive {
constexpr bool operator(int x) const
{
return x > 0;
}
};
inline constexpr Positive default_functor{};
template <typename T, typename F = decltype(default_functor)>
auto function(T x, F f = default_functor)
{
return f(x);
}
相关文章:
- 当给定默认值时,为什么此模板参数推导失败
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 为什么无法在可变参数模板中将尾随模板参数指定为默认值?
- 可变参数模板和具有继承的默认值
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 在子类函数覆盖中省略具有默认值的参数
- 函数作为具有默认值的参数
- 具有另一个具有默认值的模板参数的模板推导
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 可以通过常量引用返回默认参数的值吗?
- 对 const 引用参数使用默认值会导致崩溃
- C ,构造器中允许的参考参数默认值
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- QInput对话框参数默认值
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?