Search code examples
c++templatesfunctortemplate-specializationparentheses

() Parentheses after functor but not function pointer?


Below is a simple example, with stuff that bugs me. Also a link to an online c++ compiler with given example is here https://ide.geeksforgeeks.org/oxQd8FU2NV

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template <class T>
void PrintF (const T& printInt) { cout << printInt << " "; }

template <class T>
class PrintClass {
public:
void operator()(T elem) const {
    cout << elem << " ";
}
};

int main () {
vector<int> vect;
for (int i=1; i<10; ++i) {
    vect.push_back(i);
}


for_each (vect.begin(), vect.end(), PrintClass<int>()); cout << endl;

for_each (vect.begin(), vect.end(), PrintF<int>);      cout << endl;

//  for_each (vect.begin(), vect.end(), PrintF<int>() );  
//  won't compile because of ()  in PrintF<int>()

return 0;
}

Why can't we write PrintClass<int>() without (), like this PrintClass<int> (first for_each line) ?

And when using function (not function object) we must not use () (second for_each line),so we write like this PrintF<int> ?

How should I interpret/parse the 3rd argument in these two for_each functions ?


Solution

  • PrintF<int> is a function. We're passing the function to for_each. Putting parentheses would be incorrect, as we'd be attempting to (unsuccessfully) call the function.

    PrintClass<int> is a class. We can't pass classes around, as they're not values. We can, however, pass instances of that class around, so we make an instance of the class and pass it. The following two calls would have the same result

    for_each (vect.begin(), vect.end(), PrintClass<int>());
    

     

    PrintClass<int> myFunction = PrintClass<int>();
    for_each (vect.begin(), vect.end(), myFunction);