0

In C++ sometimes I see curly braces after objects, and also parentheses after that curly braces

Examples of curly braces:

std::transform(v.cbegin(), v.cend(), v.cbegin, v.begin(), std::plus<>{}

Question 1: What does {} mean after std::plus<> ?

Example of parentheses after curly brackets:

 std::sample(in.begin(), in.end(), std::back_inserter(out),
                5, std::mt19937{std::random_device{}()});

Question 2: What does {}() mean in std::random_device{}()

  • 3
    `T{}` is **aggregate initialization**. `std::plus<>{}` creates a (temporary) object of `std::plus<>` which is intialized with default values. `std::random_device{}()` also constructs a `random_device` with aggregate initialization and additionaly, it's `operator()` is called. – Raildex Jul 30 '22 at 07:19
  • @PabloArkadiusz This is explained in any [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or the dupes listed in the dupe list. Refer to [Dupe1](https://stackoverflow.com/questions/73164276/why-greaterint-needs-following-when-used-as-comparator-in-sorting), [Dupe2](https://stackoverflow.com/questions/18046760/syntax-for-using-stdgreater-when-calling-stdsort-in-c) and [Dupe3](https://stackoverflow.com/questions/72451130/why-dont-we-add-parenthesis-when-writing-comparator-in-c). – Jason Jul 30 '22 at 07:25
  • 1
    The curly braces are after types, not after objects. `std::random_device` is a type, adding `{}`creates an instance of it, and then `()`uses the "function call operator" of that instance. – molbdnilo Jul 30 '22 at 08:57

0 Answers0