为什么在为 STL 定义函子时必须使用 const& 参数?
Why must I use a const& parameter when defining a functor for STL?
auto cmp = [](pair<int, int> & left, pair<int, int> & right){if(left > right) return true; else return false;};
multiset<pair<int, int>, decltype(cmp)> mt(cmp);
// If I just compile the two lines above, it will work.
// But if I try to insert some elements as below, I'll get errors.
//mt.insert({0, 3});
//mt.insert({1, 1});
但是,如果我为cmp
的两个参数添加const
或删除&
,它将工作。
当我试图将元素插入mt
时,为什么我不能使用cmp
的非const
引用?
根据cppreference, cmp必须满足Compare的要求。
Compare的引用说:
与任何BinaryPredicate一样,该表达式的求值不允许调用解引用迭代器的非const成员函数。
为了防止比较器意外地改变存储元素的状态,您需要使用const引用或通过复制获取值。
编译器认为您可能会更改传递给cmp
函数的参数,因为您已经指定了输入参数的引用。然而,insert
语句传递的是不能修改的常量(编译器知道这一点)。因此不匹配。
如果你分配两个变量,然后将变量传递给你的insert()
调用,它工作吗?
相关文章:
- 不允许运算符 const 参数调用 const 成员函数
- std::p ackaged_task 应该删除带有 const 参数的复制 c'tor
- 将非 const 对象用于 const 参数
- 对可变参数模板使用 const 参数
- 为什么 QObject::d isconnect(const QMetaObject::Connection &connection) 采用 const 参数并打算修改它?
- 为什么static_assert在带有 const 参数的成员函数中不起作用?
- 如何使用 QString::replace on const& 参数?
- 将const char * const参数成员分配给新值
- 默认移动构造函数采用 const 参数
- 模板参数包无法推断"const&"参数
- const参数与const引用参数
- 重载解析不正确,const 参数的值为 0
- 无法将带有 const 参数的函数转换为函数指针?
- const参数与C 模板中的非const参考结合
- 该函数更改成员函数的const参数
- 重载比较运算符 C++,如何与 const 参数进行比较
- 为什么 const 数组优先绑定到 const T& 参数而不是 T&& 参数?
- const参数的类的只读版本
- 为什么这个 const 参数不能与非类型模板参数匹配?
- 没有匹配函数调用具有 const 参数的模板化函数