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
Answers to questions are automatically generated and may not have been reviewed.
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.