Tuesday, October 17, 2017

C++17: Fold expressions for variadic templates

C++17 added fold expressions for variadic templates. Here is an example:

#include <iostream>

template<typename... Args>
bool AllTrueRight(Args... args) { return (args && ...); }

template<typename... Args>
bool AllTrueLeft(Args... args) { return (... && args); }

template<typename... Args>
int SumUnaryRight(Args... args) { return (args + ...); }

template<typename... Args>
int SumUnaryLeft(Args... args) { return (... + args); }

template<typename... Args>
int SubBinaryRight(Args... args) { return (args - ... - 100); }

template<typename... Args>
int SubBinaryLeft(Args... args) { return (100 - ... - args); }

int main()
{
  bool bResult = false;
  int  iResult = -1;

  bResult = AllTrueRight(true, true, true, false);
  std::cout << bResult << " "  ;

  bResult = AllTrueRight(true, true, true, true);
  std::cout << bResult << " "  ;

  bResult = AllTrueLeft(true, true, true, false);
  std::cout << bResult << " "  ;

  bResult = AllTrueLeft(true, true, true, true);
  std::cout << bResult << " "  ;

  iResult = SumUnaryLeft(1, 2, 3, 4);
  std::cout << iResult << " "  ;

  iResult = SumUnaryRight(1, 2, 3, 4);
  std::cout << iResult << " "  ;

  iResult = SubBinaryRight(10, 9, 8); // (10-(9-(8-100))) = 10-(9+92) = 10 - 101 = -91
  std::cout << iResult << " "  ;

  iResult = SubBinaryLeft(10, 9, 8); // (((100-10)-9)-8) = (90-9)-8 = 81-8 = 73
  std::cout << iResult << " "  ;

  std::cout << std::endl;
  return 0;
}
// Output: 0 1 0 1 10 10 -91 73
Notes:
1) Needed to use: gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)
2) Commandline: g++ -std=c++17 *.cpp
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/language/fold

No comments:

Post a Comment