0

I have a question regarding the following piece of code.

template <typename T>
struct DisplayElementKeepCount
{
    int m_nCount;
    DisplayElementKeepCount () { m_nCount = 0; }
    void operator () (const T& element){++ m_nCount; cout<<element<<‘ ‘;}
};

when calling, it is written as:

DisplayElementKeepCount <int> mResult;
mResult = for_each ( vecIntegers.begin (), vecIntegers.end (), DisplayElementKeepCount <int> () );

I don't quite understand, because operator() needs a parameter "element", but it was not included when being called. why?

The example of IsMultiple actually gives a parameter when called. Why are these two different??

template <typename numberType>
struct IsMultiple
{
    numberType m_Divisor;
    IsMultiple (const numberType& divisor)
    {
        m_Divisor = divisor;
    }
    
    // The comparator of type: bool f(x)
    bool operator () (const numberType& element) const
    {
        // Check if the dividend is a multiple of the divisor
        return ((element % m_Divisor) == 0);
    }
};
...
vector <int>::iterator iElement;
iElement = find_if ( vecIntegers.begin (), vecIntegers.end (), 
IsMultiple <int> (4) );
1
  • 1
    Your second example is providing a parameter to the constructor of IsMultiple, not operator(). The parameter to operator() is passed to the functor inside the algorithm for each element in the range.
    – user657267
    Commented Apr 16, 2015 at 0:55

1 Answer 1

2

In your first example DisplayElementKeepCount has a default constructor (which takes zero parameters) and you're using it.

for_each ( vecIntegers.begin (), vecIntegers.end (), DisplayElementKeepCount <int> () );
                                                                   //  Constructor ^^

If you were calling operator() it would look like the following.

DisplayElementKeepCount<int>()(5)
             // Constructor ^^
                           // ^^^ calling operator() on the unnamed instance

In your second example IsMultiple has a constructor which takes a single parameter.

find_if ( vecIntegers.begin (), vecIntegers.end (), IsMultiple <int> (4) );
                                                      // Constructor ^^^

Again, if you were calling operator() it would look like the following.

IsMultiple<int>(4)(2)
// Constructor ^^^
               // ^^^ calling operator() on the unnamed instance
1
  • I appreciate your explanation. But I still have a question here. According to your comment, operator() was not called, only constructor was called. Is it correct?
    – Sarah
    Commented Apr 18, 2015 at 12:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.