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?
The version with the parameter given will work as well.
Yes, using the template will be more efficient, since
Dis always evaluated at compile time, as it's aconstexpr.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).