c++ - Stockfish 12 源代码 : Templates replacing function parameters

标签 c++ templates bitboard

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/

相关文章:

c++ - 如何调试无痕崩溃

c++ - 'choose<bool,typename,typename>' 是否有标准构造?

swift - 有没有办法反转 UInt64 中的位顺序?

c - 连接 5 游戏的位板?

c++ - 在使用位板的国际象棋引擎中,如何检测边缘?

c++ - 堆损坏但仅在笔记本电脑上编译时

c++ - 输出 cout 是感叹号。 C++

c++ - 将指针返回到堆栈缓冲区

javascript - meteor : best practice for modifying Mongo query result before template takes it?

c++ - 类名没有命名类型 C++