44

This code is from C++ primer p.446:

return hash<string>() (sd.isbn());

I don't understand the return expression with two pairs of parentheses. There's no similar syntax in front of the book.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
tocrafty
  • 561
  • 4
  • 9
  • 1
    Hard to tell without context – Treycos Oct 13 '16 at 14:37
  • 2
    Depends on what `hash()` returns. If it's returning a class with an overridden call operator, there's nothing special with that. – πάντα ῥεῖ Oct 13 '16 at 14:38
  • 2
    In C++11 and onward, you can use `std::hash{}` (ie, braces instead of parentheses) to build an object. It makes differentiating between object construction and function calls easier. – Matthieu M. Oct 13 '16 at 15:41
  • 2
    It's amusing how Cpp is full of those hard to understand tidbits. I deeply respect those who work primarily on this language - you need a huge deal of skill and memory to be a good C++ developer! – T. Sar Oct 13 '16 at 17:23
  • 3
    @ThalesPereira a huge deal of skill and memory is also useful to be a good C++ compiler – Harrison Paine Oct 13 '16 at 20:08
  • @ThalesPereira Most modern languages have things like this. For instance, Javascript IIFE. Although I admit that C++ templates add an extra opportunity for complex syntax. But if you just learn to break expressions down into their components, and understand each of them, things become pretty straightforward. – Barmar Oct 18 '16 at 18:59

1 Answers1

55

std::hash is a class type. What you are doing here is constructing a temporary std::hash with hash<string>() and then (sd.isbn()) calls the operator() of that temporary passing it sd.isbn().

It would be the same as

std::hash<std::string> temp;
return temp(sd.isbn());

For more reading on using objects that have a operator() see: C++ Functors - and their uses

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 2
    To add to this good answer. The `temp(sd.isbn())` might seem confusing here because it's an object. The object is basically used as a function object, a [functor](http://stackoverflow.com/questions/356950/c-functors-and-their-uses). – Hatted Rooster Oct 13 '16 at 14:44
  • @GillBates Good call. Added a link in the answer. – NathanOliver Oct 13 '16 at 14:47
  • 3
    I'd consider this another good argument for curly-bracket initialization to clarify that you're constructing an object, e.g.: `return hash{} (sd.isbn());` – Drew Dormann Oct 19 '16 at 01:16