1 // Copyright 2018 The Fuchsia Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "function_example2.h" 6 7 #include <lib/fit/function.h> 8 9 // This example demonstrates using |fit::function| to capture a member 10 // function (add) and applying it to each element of a vector. 11 namespace function_example2 { 12 13 class accumulator { 14 public: add(int value)15 void add(int value) { 16 sum += value; 17 } 18 19 int sum = 0; 20 }; 21 count_to_ten(fit::function<void (int)> fn)22void count_to_ten(fit::function<void(int)> fn) { 23 for (int i = 1; i <= 10; i++) { 24 fn(i); 25 } 26 } 27 sum_to_ten()28int sum_to_ten() { 29 accumulator accum; 30 count_to_ten(fit::bind_member(&accum, &accumulator::add)); 31 return accum.sum; 32 } 33 run()34void run() { 35 assert(sum_to_ten() == 55); 36 } 37 38 } // namespace function_example2 39