【C++ troubleshooting】A case about decltype

本文探讨了C++中next_permutation函数模板的实现细节,并通过具体实例解析了其中涉及的类型推导与std::lower_bound使用时可能遇到的编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

template <typename iter_t>
bool next_permutation(iter_t beg, iter_t end) {
//
    if (beg == end || beg + 1 == end) {
        return false;
    }
    //在白板上写代码别忘了加 }

    for (int *i = end - 2; i >= beg; --i) {
        auto iter = std::lower_bound(i + 1, end, *i, std::greater<decltype(*beg)>{});
        if (iter != i + 1) {
            std::swap(*(iter - 1), *i);
            std::reverse(i + 1, end);
            return true;
        }
    }
    return false;
}
ptr_t ptr;
*ptr;

As we know, in C++, for a variable ptr of a pointer (or iterator) type, the expression *ptr returns a reference to the object that ptr points to.

Suppose the object that ptr points to is of type T, then decltype(*ptr) will yield the type T&.

So, in the above code, the line

auto iter = std::lower_bound(i + 1, end, *i, std::greater<decltype(*beg)>{});

becomes

auto iter = std::lower_bound(i + 1, end, *i, std::greater<int&>{});

when the function template next_permutation is instantiated.

However, such an instantiation of std::lower_bound will not compile.

Let's see the compile error:

In file 
.../include/c++/8.3.0/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_comp_val<_compare>::operator()(_Iterator, _Value&) [with _Iterator = int*; _Value = const int; _Compare = std::greater<int&>]':
.../include/c++/8.3.0/bits/predefined_ops.h:177:11: error: no match for call to '(std::greater<int&>) (int&, const int&)'
  { return bool(_M_comp(*__it, __val)); }
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~

In file 
.../include/c++/8.3.0/bits/predefined_ops.h:177:11:error: binding reference of type 'int&' to 'const int' discards qualifiers
  { return bool(_M_comp(*__it, __val)); }
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~

将其中提到的函数片段,还原如下

  template<typename _Compare>
    struct _Iter_comp_val
    {
      _Compare _M_comp;
      
      // constructors
     
      template<typename _Iterator, typename _Value>
    bool
    operator()(_Iterator __it, _Value& __val)
    { return bool(_M_comp(*__it, __val)); }
    };

这个问题我还没搞懂。

转载于:https://www.cnblogs.com/Patt/p/10597056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值