c++ - 以模板化函数作为参数的 STL 算法

标签 c++ c++11 stl-algorithm template-function

如何将模板化函数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/

相关文章:

c++ - 使用带有 valarray 的 C++ 标准库算法

c++ - 为什么虚幻引擎中的变量为空?

c++ - std::generate 不适用于 std::vector

c++ - 动态分配的数组和堆损坏

c++ - 从编译的可执行文件中执行函数

c++ - 防止表达式模板绑定(bind)到右值引用

c++ - 扫描位数组以获取多个位的模式

c++ - 使用 for_each() 和 lambda 函数打印 C 风格数组的模板函数

c++ - 调用析构函数方法比较

c++ - 存储带有日语文本的字符串并写入文件