我真的很难理解这些宣言
static bool compare ( const shared_ptr<int> lhs,const shared_ptr<int> rhs )
{ return (*lhs) < (*rhs) ; }
multiset<shared_ptr<int>,decltype(compare)*> item{ compare } ;
如果我在decltype(比较)后没有给出指针,它会给出错误吗?为什么错误?为什么我应该提供bool *而不是bool作为谓词之类的算法函数,再次讨论在{compare}项中使用花括号进行比较的好处?它会按排序顺序在multiset中插入对象吗?如果我不给{compare}会发生什么?
答案 0 :(得分:3)
multiset
第二个参数所期望的类型是 Predicate 。这是对象c
的类型,以便c(lhs, rhs)
返回可转换为bool
的内容。
compare
和decltype(compare)
的类型为bool(shared_ptr<int>, shared_ptr<int>)
,函数类型。不能有函数类型的值,但指针和引用的值可以是函数类型 。这就是你需要*
的原因。 (实际上,有函数类型的值,并且是那些你声明为函数的东西,但是除了调用它们并获取它们的地址之外,它们不能被创建,复制,也没有任何东西。)总结:
decltype(compare)* ==> bool (*)(shared_ptr<int>, shared_ptr<int>)
这是一个指向函数的指针,该函数按值shared_ptr<int>
获取两个bool
并返回multiset
。然后,在items{ compare }; // value
构造函数中,为其指定该类型的值:
items{ &compare }; // pointer to function compare
或更具体地说,函数类型的值衰减到函数指针类型。所以让我们明确指出:
struct shared_ptr_compare
{
bool operator()(std::shared_ptr<int> const& lhs, std::shared_ptr<int> const& rhs) const
{ return /*...*/; }
};
multiset<shared_ptr<int>, shared_ptr_compare> item; // no need to initialize
// shared_ptr_compare with anything, a default value will do just fine
如果你没有给它任何东西,那么它将是一个空指针,当试图调用它进行比较时你的应用程序会崩溃。
总之,你选择了一个复杂案例的地狱(我已经跳过了一些我应该提到的事情)。这是一种更简单的方法:
const
注意:我删除了顶级shared_ptr<int> const&
修饰符,因为它对函数参数没有影响,它只向函数体发出信号,表示值无法更改。所以它确实有意义,但复杂的解释类型。
注意2 :您应该将这些参数设为const shared_ptr<int>&
(与{{1}}相同),因为您实际上并不需要副本,而且这些副本必须保留引用计数器,它是必须在线程之间同步的操作。