What does static_cast mean when it's followed by two pairs of parentheses?

2.2k Views Asked by At

What does this say:

return static_cast<Hasher &>(*this)(key);

?

I can't tell whether *this or key is passed to static_cast. I looked around and found this answer, but unlike what I'm stuck on, there's nothing inside the first pair of parentheses.

2

There are 2 best solutions below

8
On

I can't tell whether *this or key is passed to static_cast

If you're unsure, you can just look up the syntax.

In the informal documentation, the only available syntax for static_cast is:

static_cast < new-type > ( expression )

and the same is true in any standard draft you compare.

So there is no static_cast<T>(X)(Y) syntax, and the only possible interpretation is:

  • new-type = Hasher&
  • expression = *this

and the overall statement is equivalent to

Hasher& __tmp = static_cast<Hasher &>(*this);
return __tmp(key);

In the skarupke/flat_hash_map code you linked, the interpretation is that this class has a function call operator inherited from the private base class Hasher, and it wants to call that explicitly - ie, Hasher::operator() rather than any other inherited operator(). You'll note the same mechanism is used to explicitly call the other privately-inherited function call operators.

It would be more legible if it used a different function name for each of these policy type parameters, but then you couldn't use std::equal_to directly for the Equal parameter, for example.

It might also be more legible if it used data members rather than private inheritance for Hasher, Equal etc. but this way is chosen to allow the empty base-class optimization for stateless policies.

0
On

The statement is parsed as

return (static_cast<Hasher &>(*this))(key);

So, the argument to static_cast is *this. Then the result of the cast, let's call it x, is used as postfix-expression in a function call with key as argument, i.e. x(key), the result of which is returned.