0

我对以下代码有疑问。

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

调用的时候写成:

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

不是很明白,因为operator()需要一个参数“元素”,但是调用的时候没有包含。为什么?

IsMultiple 的示例在调用时实际上给出了一个参数。为什么这两个不一样??

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) );
4

1 回答 1

2

在您的第一个示例DisplayElementKeepCount中,有一个默认构造函数(它采用零参数)并且您正在使用它。

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

如果您正在调用operator()它,它将如下所示。

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

在您的第二个示例IsMultiple中,有一个带有单个参数的构造函数。

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

同样,如果您正在调用operator()它,它将如下所示。

IsMultiple<int>(4)(2)
// Constructor ^^^
               // ^^^ calling operator() on the unnamed instance
于 2015-04-16T01:42:13.110 回答