如何将模板化函数与STL 中提供的算法一起使用<algorithm>
?
例如,此代码无法编译,因为编译器无法推断出 predicate
的模板参数。功能:
#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;
}
最佳答案
几种方式:包括
明确提供类型
predicate<std::string::value_type>
使用 lambda
[](auto&&e) { predicate(e); }
关于c++ - 以模板化函数作为参数的 STL 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792672/