Templated operator() in Functors

Can the operator() in a functor be a template function?

Yes, the operator() in a functor can be a template function. This allows the functor to accept arguments of different types, similar to how a regular function template works.

Here's an example of a functor with a templated operator():

#include <iostream>
#include <string>

class Printer {
 public:
  template <typename T>
  void operator()(T value) const {
    std::cout << value << "\n";  
  }
};

int main() {
  Printer print;

  // Prints an int
  print(42);
  
  // Prints a double
  print(3.14);
  
  // Prints a const char*
  print("Hello");

  // Prints a std::string
  print(std::string("World"));
}
42
3.14
Hello
World

In this example, the Printer functor's operator() is a template function that accepts any type T. When operator() is called with an argument, the template parameter T is deduced based on the type of the argument.

This allows the Printer functor to be used with various types, such as int, double, const char*, and std::string, without the need to explicitly specify the type.

Templated operator() functions in functors are particularly useful when writing generic algorithms that need to work with callable objects accepting different types of arguments.

For instance, the std::transform algorithm could be used with a functor that has a templated operator() to transform elements of different types:

#include <algorithm>
#include <iostream>
#include <vector>

class Square {
 public:
  template <typename T>
  T operator()(T value) const {
    return value * value;  
  }
};

int main() {
  std::vector<int> vi{1, 2, 3};
  std::vector<double> vd{1.1, 2.2, 3.3};

  std::transform(vi.begin(), vi.end(),
    vi.begin(), Square());
  std::transform(vd.begin(), vd.end(),
    vd.begin(), Square());

  for (int i : vi) {
    std::cout << i << " ";
  }
  std::cout << "\n";

  for (double d : vd) {
    std::cout << d << " ";
  }
  std::cout << "\n";
}
1 4 9
1.21 4.84 10.89

Function Objects (Functors)

This lesson introduces function objects, or functors. This concept allows us to create objects that can be used as functions, including state management and parameter handling.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Functors vs Lambda Expressions
When should I use a functor instead of a lambda expression in C++?
Non-Operator Overloads in Functors
Can a functor class contain non-operator overloads, and how do I call them?
Functors and Inheritance
Can a derived class override the operator() of a base functor class?
Functor vs Function Performance
Is there a performance difference between using functors and regular functions?
Capturing this in Functors
Can a functor capture the this pointer, and what are the implications?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant