std::greater{} 和 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>是所谓的"透明"的专门化。推导其参数的比较器,详细信息请参见其参考。

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

std::greater<>,又名std::greater<void>,有一个模板引用auto operator()(T const&, U const&) const,该模板调用>并推导其返回值。

在c++11及更早版本中,greater<void><>不能工作。

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

在其他上下文中,void版本将允许您比较不同的类型(使用合适的<或转换重载),并允许您忽略正在比较的类型。

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

最新更新