Back to TILs

C++ functor

Date: 2019-09-13Last modified: 2024-11-02

Table of contents

class MyFunctor {
 public:
  int operator()(int x) { return x * 2; }
};

class Matcher {
  int target;

 public:
  Matcher(int m) : target(m) {}
  bool operator()(int x) { return x == target; }
};

class MultBy {
  int mult = 1;
  MultBy();

 public:
  MultBy(int n) : mult(n) { std::cout << "MultBy(" << mult << ") Ctor\n"; }
  int operator()(int n) const {
    return mult * n;
  }
};

int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
  MyFunctor doubler;
  assert(doubler(5) == 10);

  Matcher Is5(5);
  auto n = 5;
  assert(Is5(n));  // o mesmo que  n == 5

  const MultBy times4(4);
  const MultBy times10(10);
  const MultBy times15(15);

  std::cout << "times4(5) = " << times4(5) << "\n";
  std::cout << "times4(15) = " << times4(15) << "\n";
  std::cout << "times10(5) = " << times10(5) << "\n";
  std::cout << "times10(15) = " << times10(15) << "\n";
  std::cout << "times15(5) = " << times15(5) << "\n";
  std::cout << "times15(15) = " << times15(15) << "\n";

  return 0;
}

Possible output

MultBy(4) Ctor
MultBy(10) Ctor
MultBy(15) Ctor
times4(5) = 20
times4(15) = 60
times10(5) = 50
times10(15) = 150
times15(5) = 75
times15(15) = 225

References