二進位制摺疊

二進位制摺疊基本上是一元摺疊 ,有一個額外的引數。

有兩種二進位制摺疊:

  • 二進位制折 - (value op ... op pack) - 擴充套件如下:

    (((Value op Pack1) op Pack2) op ...) op PackN
    
  • Binary Right Fold (pack op ... op value) - 擴充套件如下:

    Pack1 op (... op (Pack(N-1) op (PackN op Value)))
    

這是一個例子:

template<typename... Ts>
int removeFrom(int num, Ts... args)
{
    return (num - ... - args); //Binary left fold
    // Note that a binary right fold cannot be used
    // due to the lack of associativity of operator-
}

int result = removeFrom(1000, 5, 10, 15); //'result' is 1000 - 5 - 10 - 15 = 970