0

Alas, it's hard to google for symbols like braces.

I came across this code:

#include <functional>
#include <iostream>
 
template <typename A, typename B, typename C = std::less<>>
bool fun(A a, B b, C cmp = C{})
{
    return cmp(a, b);
}
 
int main()
{
    std::cout
      << std::boolalpha
      << fun(1, 2)   << ' ' // true
      << fun(1.0, 1) << ' ' // false
      << fun(1, 2.0) << ' ' // true
      << std::less<int>{}(5, 5.6)    << ' ' // false: 5 < 5 (warn: implicit conversion)
      << std::less<double>{}(5, 5.6) << ' ' // true: 5.0 < 5.6
      << std::less<int>{}(5.6, 5.7)  << ' ' // false: 5 < 5 (warn: implicit conversion)
      << std::less{}(5, 5.6)         << ' ' // true: less<void>: 5.0 < 5.6
      << '\n';
}

in https://en.cppreference.com/w/cpp/utility/functional/less.

What do braces in the statements C{}, std::less<int>{}(5, 5.6) mean?

Bubaya
  • 615
  • 3
  • 13
  • 2
    uniform initialization https://en.cppreference.com/w/cpp/language/initialization – apple apple Apr 28 '22 at 13:48
  • same as [this](https://stackoverflow.com/questions/40024008/how-to-understand-two-pairs-of-parentheses-in-this-code-fragment) but using `{}` instead of `()`. – NathanOliver Apr 28 '22 at 13:50
  • 1
    Related: [https://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization](https://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization) – drescherjm Apr 28 '22 at 13:52

1 Answers1

0

it create an instance of std::less<int>

then pass 5,5.6 as the parameter to it's bool operator()(const int&, const int&)


it's roughly the same as

auto temp = std::less<int>{};
std::cout << temp(5, 5.6);
apple apple
  • 10,292
  • 2
  • 16
  • 36