Search code examples
c++stlmem-fun

STL for_each complaining about argument list


As part of a homework assignment, we are supposed to map the occurrence of each character in a map. Our function is supposed to use std::for_each and pass in the character to be evaluated.

My function is:

std::for_each(document_.begin(), 
              document_.end(), 
              std::mem_fun(&CharStatistics::fillMap));

document_ is a string, and the fillMap function is defined like

void CharStatistics::fillMap(char ch)
{
    ch = tolower(ch);
    ++chars_.find(ch)->second;
}

chars_ is declared as std::map<char, unsigned int> chars_;.

I figure this should work, but the compiler is complaining

error C2064: term does not evaluate to a function taking 1 arguments

Which confuses me, because when I look at the argument list

_Fn1=std::mem_fun1_t<void,CharStatistics,char>,
1>            _Elem=char,
1>            _Traits=std::char_traits<char>,
1>            _Alloc=std::allocator<char>,
1>            _Result=void,
1>            _Ty=CharStatistics,
1>            _Arg=char,
1>            _InIt=std::_String_iterator<char,std::char_traits<char>,std::allocator<char>>

it looks fine to me. _Elem is a char and my function accepts a char. The iterator is nothing else than a char *

What am I doing wrong?


Solution

  • CharStatistics::fillMap is not a function taking 1 argument. it's member function and so it has implicit first argument - pointer to class instance.

    in code:

    std::for_each(document_.begin(), 
                  document_.end(), 
                  std::mem_fun(&CharStatistics::fillMap));
    

    for_each don't know on which instance you'd like to call CharStatistics::fillMap, you didn't specify it. you need to bind it with any CharStatistics instance, e.g.:

    std::bind1st(std::mem_fun(&CharStatistics::fillMap), &char_statistics_instance)