The code is shown here:
class Basket{
public:
/*other contents*/
private:
// function to compare shared_ptrs needed by the multiset member
static bool compare(const std::shared_ptr<Quote> &lhs,
const std::shared_ptr<Quote> &rhs)
{ return lhs->isbn() < rhs->isbn(); }
// multiset to hold multiple quotes, ordered by the compare member
std::multiset<std::shared_ptr<Quote>, decltype(compare)*>
items{compare};
};
We initialize our multiset through an in-class initializer. Commonly we put a same class object in the curly bracket. Why a function can be put here? I can't understand;
It's explained in the book C++ primer like it: The multiset will use a function with the same type as our compare member to order the elements. The multiset member is named items, and we’re initializing items to use our compare function.
I can understand the logic, but what is the syntax used here?
items{compare};
is a call to one of the overloads of the constructor of std::mulitset.Which one of the overloads to use is decided by the compiler from looking at your argument type:
compare
matches the description of a "comparison function object" (see link), so the second invocation is used.It is a pointer to a function, taking two values as parameters and returning a boolean is the main point here. That function can then be later called by the multiset object to sort its members. Look up "callback functions" if you want to learn more about this concept. See here for a start: Callback functions in C++
What you're refering to with
would be using the copy-constructor (no. 6 in the link). Just another way to create the same type of object.
There are questions here on SO about using a constructor with
{}
vs()
if that is part of the confusion: What's the difference between parentheses and braces in c++ when constructing objects