std::greater{} 和 std::greater<int>() 有什么区别?

What is the diffrence between std::greater{} and std::greater<int>()?

有人写

std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater{});

有些人是这样写的

std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater<int>());

std::greater{}std::greater<int>()有什么区别?

这是 C++14 的新内容,这导致两个完全不同的 类。

在 C++14 中,std::greater 获取其模板参数的默认值:void.

你最终得到 std::greater<void>std::greater<int>

std::greater<void> 是推导其参数的 so-called "transparent" comparator 的特化,请参阅其参考以获取更多信息。

std::greater<int> 有一个 bool operator()(int const&,int const&) const 调用 >.

std::greater<>,又名 std::greater<void>,有一个模板引用 auto operator()(T const&, U const&) const,它调用 > 并推导出它的 return 值。

及更早版本中,greater<void><> 将不起作用。

实际上这里没有区别。在任何非零优化下,比较的两个版本都将被内联。

在其他情况下,void 版本可以让您比较不同的类型(使用合适的 < 或转换重载),并让您忽略正在比较的类型。

另一个重要的细节是 <void> 宣传了一个 is_transparent 标签。当传递给像 std::map 这样的容器时,它会将一些方法更改为具有模板参数。这允许使用 std::string 键而不强制查找字符串成为相同的对象类型,这样可以节省副本和分配。