Search code examples
c++c++11stl-algorithmtemplate-function

STL algorithms with templated functions as parameter


How is it possible to use a templated functions with the STL provided algorithms in <algorithm>? For example, this code does not compile because compiler can't deduce template parameters for the predicate function:

#include <iostream>
#include <algorithm>

template< typename CharType >
bool predicate( const CharType& c )
{
    return c == '0';
}

std::string
process_string( const std::string& str )
{
    std::string result;
    std::copy_if( str.begin( ),
                  str.end( ),
                  std::back_inserter( result ),
                  predicate );
    return result;
}

int main()
{
    std::cout << process_string("AK0NNDK0ASDAS0") << std::endl;
    return 0;
}

Solution

  • You can provide the type: predicate<std::string::value_type>