【问题标题】:C++17 template argument deduction mystery [duplicate]C ++ 17模板参数推导之谜[重复]
【发布时间】:2020-01-07 20:05:47
【问题描述】:

在 C++17 中,您可以这样做:

#include <iostream>
#include <algorithm>
#include <functional>

int main()
{
    double values[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 };

    // Notice this:
    std::sort(values, values+5, std::greater());

    for(double v: values) std::cout << v << " ";
    std::cout << "\n";
}

您实际上不需要指定std::greater 的模板参数。 会自动推导出为double。真是太好了。

但是等等……怎么样?!?

没有什么告诉std::greater模板参数应该是 double 类型。它不采用任何构造函数参数或任何东西。 而std::sort()的声明表面上是这样的:

template<class RandomIt, class Compare>
void sort(RandomIt first, RandomIt last, Compare comp);

所以没有任何东西告诉它应该是双倍的。

那怎么办?

【问题讨论】:

  • 我在移动设备上,所以可以抢到:它是 std::greater&lt;&gt;,它有一个 operator() 模板而不是固定类型。
  • What are transparent comparators? 的可能重复项。 tl; 博士 - 昆汀所说的。比较器不是一个类模板,它的操作符 () 是一个模板。
  • 我不同意这是重复的。链接的"duplicate" 很好地讨论了透明比较器,以及它们是如何定义的——但它没有回答 OP 的问题——“这段代码是如何工作的”
  • @MarshallClow:它可以工作因为透明比较器存在;一旦您了解&lt;class=void&gt;,这里的行为就很明显了。这够好吗?
  • @DavisHerring 我认为缺少一个链接:拥有默认模板参数不会使模板参数列表 (&lt;&gt;) 可省略。其实就是CTAD的威力,“复制品”中没有提到。

标签: c++ templates c++17


【解决方案1】:

std::greater 有两个不同的定义。 一个需要类型的模板参数,另一个不需要。

您正在使用第二个。

这就是std::greater 的样子(去掉constexpr 和noexcept 等修饰符以及不同的返回类型):

template <typename T = void>
struct greater
{
    bool operator () (const T& x, const T& y) { return x > y; }
};

template <>
struct greater<void>
{
    template <typename T1, typename T2>
    bool operator () (const T1& x, const T2& y) { return x > y; }
    typedef void is_transparent;
};

【讨论】:

  • 是的,但是如何 greater() 会排在第二位?
  • 好吧,它不可能是第一个——因为你没有提供模板参数;所以它必须是第二个。
  • 哎呀。谢谢,戴维斯。固定。
  • @MarshallClow:cpplearner 的观点(也可能是你的观点):这里必须提到 CTAD。
  • 这个答案,至少就其本身而言,是行不通的。我试过了,当我尝试像“std::sort(values, values+5, greater());”一样使用它时,我得到了错误“'(' token 之前缺少模板参数”;显然它期望它像“greater()”一样使用。但是,如我的原始问题所示,std::greater 不需要空括号。因此我的问题仍未得到解答。我也必须反对将其标记为重复到其他帖子,因为其他帖子也不回答问题。
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
  • 2017-12-30
  • 2013-04-24
相关资源
最近更新 更多