自 Stockfish是评价最高的国际象棋引擎,众所周知它非常高效,我决定打开它的源代码并尝试了解它是如何工作的。
我遇到了这段代码,只需将位板移动到某个方向(北、南、东...)
取自 STOCKFISH 12 来源: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
调用函数shift< direction >(bitboard);
在这种情况下需要什么模板,为什么会像constexpr Bitboard shift(Bitboard b,Direction D) {
return D == NORTH ? b << 8 : D == SOUTH ? b >> 8
// ...........
}
不行?第一种方式是否更有效?
最佳答案
What is the need to have a template in this context, and why would something like
// omitted code
not work?
具有给定参数的版本也将起作用。
Is the first way more efficient in any way?
是的,使用模板会更有效率,因为
D
总是在编译时计算,因为它是 constexpr
.在运行时评估总是需要一个函数调用(尽管它可以被内联),以及从堆栈中评估参数(这可能会花费一些寄存器操作,即使是内联的)。
关于c++ - Stockfish 12 源代码 : Templates replacing function parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64193811/