[cpp] Multi args

Viewer

copydownloadembedprintName: Multi args
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct add{
  5.     int sum = 0;
  6.  
  7.     add(int i) : sum(i) {}
  8.  
  9.     add& operator()(int i){
  10.         sum += i;
  11.         return (*this);
  12.     }
  13.  
  14.     int operator()(){
  15.         return sum;
  16.     };
  17.  
  18. };
  19.  
  20. template<typename VALUE>
  21. VALUE addVec(std::initializer_list<VALUE> &&list){
  22.     std::vector<VALUE> vec = list;
  23.     VALUE sum = 0;
  24.     for (auto& iter : vec)
  25.         sum += iter;
  26.     return sum;
  27. }
  28.  
  29.  
  30. int main(){
  31.  
  32.     // ADD STRUCT
  33.     int a = add(4)(5)(6)(7)();
  34.     std::cout << "add: " << a << std::endl;
  35.  
  36.     // ADD VEC
  37.     int b = addVec({4567});
  38.     std::cout << "addVec: " << b << std::endl;
  39.  
  40.  
  41.   /* Lista inicjalizatora wymaga C++11
  42.         OUTPUT:
  43.       add: 22
  44.       addVec: 22
  45.   */
  46. }

Editor

You can edit this paste and save as new:


File Description
  • Multi args
  • Paste Code
  • 29 Oct-2020
  • 780 Bytes
You can Share it: