【问题标题】:What is the use of decltype in this code ?此代码中 decltype 的用途是什么?
【发布时间】:2015-01-21 12:17:15
【问题描述】:

我写了一小段代码,它会抛出很多错误,如果我不使用 decltype 关键字而使用 decltype 关键字,它编译得很好:-

   std::function<bool(int,int)> f2 = [dist](int n1,int n2) {if(dist[n1] < dist[n2]) return false ; return true ; } ; 
        priority_queue<int,vector<int>,decltype(f2)>  pq(f2)  ; 

在这里,我想用我自己的自定义比较函数声明一个priority_queue,所以我决定使用std::function 和lambdas。
另外,diststd::vector&lt;int&gt;

但奇怪的是,如果我将 decltype(f2) 替换为 f2,代码会出错。

为什么会这样?

【问题讨论】:

  • 作为记录,这不是priority_queue 的有效比较器。这不是严格的弱排序。

标签: c++ c++11 compilation compiler-errors decltype


【解决方案1】:

priority_queue模板类的第三个参数是谓词类型。这里decltype(f2)实际上给出了f2的类型,而不是decltype你可以写std::function&lt;bool(int,int)&gt;

【讨论】:

  • 但是我们不应该只给出 f2 而不是 std::function&lt;bool(int,int)&gt;
  • @ps06756 不,f2 是这种类型的对象。
  • f2 是一个对象。您不能将对象用于需要类型的模板参数。对象不是类型。类型不是对象。
【解决方案2】:

参考documentationspriority_queue必须接收3种类型。这里,intvector&lt;int&gt; 类型后面是 f2 类型,而不是 f2。 decltype 给你一个类型而不是一个变量。

请注意:decltype = typeof 但以官方方式

【讨论】:

    【解决方案3】:

    我不知道你为什么使用 std::function&lt;bool(int,int)&gt; 作为你的 lambda 函数的返回类型,我会简单地使用 auto 代替,因为 std::function 在类型构造期间也可能会提供一些开销。如果您不知道它的作用,让编译器为您做出最佳选择。

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多