如果您经常这样做,您可能需要编写一个透明函子包装器:
struct my_max {
template<class T>
const T& operator()(const T& a, const T& b) const{
return std::max(a, b);
}
};
然后你可以简单地做
std::transform(v.begin(), v.end(), v2.begin(), v2.begin(), my_max());
当您需要时,而不是每次都编写 lambda 或强制转换。这基本上与透明运算符函子的想法相同 - 让模板参数在实际调用站点推导,而不是在创建函子时显式指定。
如果你想让这个更高级,你甚至可以operator()
采用异构类型并添加完美转发并使用尾随返回类型:
struct my_max {
template<class T, class U>
constexpr auto operator()( T&& t, U&& u ) const
-> decltype(t < u ? std::forward<U>(u) : std::forward<T>(t)){
return t < u ? std::forward<U>(u) : std::forward<T>(t);
}
};
在 C++14 中,这被简化为
struct my_max {
template<class T, class U>
constexpr decltype(auto) operator()( T&& t, U&& u ) const{
return t < u ? std::forward<U>(u) : std::forward<T>(t);
}
};