Stockfish 12 source code: Templates replacing function parameters

199 views Asked by At

Since Stockfish is the highest rated chess engine, and it's known to be quite CPU-effiecient I decided to open its source code and try to understand and see how it works.

I came across this snippet of code, simply shifts a bitboard to a certain direction (north, south, east...)

TAKEN FROM STOCKFISH 12 SOURCE: Download

template<Direction D>
constexpr Bitboard shift(Bitboard b) {
  return  D == NORTH      ?  b             << 8 : D == SOUTH      ?  b             >> 8
  // ...........
}
// Bitboard is a type definition for uint64_t

Calling the function

shift< direction >(bitboard);

What is the need to have a template in this context, and why would something like

constexpr Bitboard shift(Bitboard b,Direction D) {
  return  D == NORTH      ?  b             << 8 : D == SOUTH      ?  b             >> 8
  // ...........
}

not work? Is the first way more efficient in any way?

1

There are 1 answers

0
πάντα ῥεῖ On BEST ANSWER

What is the need to have a template in this context, and why would something like

// omitted code

not work?

The version with the parameter given will work as well.

Is the first way more efficient in any way?

Yes, using the template will be more efficient, since D is always evaluated at compile time, as it's a constexpr.

Evaluating at runtime would always require a function call (though it could be inlined), and evaluation of the parameter from the stack (which may cost a few register operations, even if inlined).