如何绑定模板函数

how to bind a template function

本文关键字:函数 绑定 何绑定      更新时间:2023-10-16

大家好!

我想在一个字符串向量中找到一个特定的元素,忽略大小写:

#include <iostream>
#include <string>
#include <vector>
#include "boost/algorithm/string.hpp"
#include "boost/bind.hpp"
using std::string;
using std::vector;
bool icmp(const string& str1, const string& str2)
{
    return boost::iequals(str1, str2);
}
int main(int argc, char* argv[])
{
    vector<string> vec;
    vec.push_back("test");
//  if (std::find_if(vec.begin(), vec.end(), boost::bind(&boost::iequals<string,string>, "TEST", _1)) != vec.end()) <-- does not compile
    if (std::find_if(vec.begin(), vec.end(), boost::bind(&icmp, "TEST", _1)) != vec.end())
        std::cout << "found" << std::endl;
    return 0;
}

到目前为止,这是正常工作的,但我想知道的是,如果有可能摆脱额外的函数(icmp())并直接调用equals(模板函数)(就像在注释行中一样)。

提前感谢!

添加模板参数和默认locale参数在我的机器上有效。

if (std::find_if(vec.begin(), vec.end(), boost::bind(&boost::iequals<string,string>, "TEST", _1, std::locale())) != vec.end())
        std::cout << "found" << std::endl;

我相信这不是你所希望的,但这似乎是我唯一能解决的问题
(使用g++ c++03模式):

typedef bool (*fptr)(const std::string&, const std::string&);

if (std::find_if(vec.begin(), vec.end(), 
    boost::bind((fptr) &boost::iequals<string,string>, "TEST", _1)
) != vec.end())

使用boost lambda:)

#include <iostream>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <algorithm>
#include <vector>
using namespace std;
using namespace boost::lambda;
int main()
{
    vector<string> vec;
    vec.push_back("TEST");
    vec.push_back("test");
    vector<string>::iterator it;
    it = find_if(vec.begin(),vec.end(),_1 == "test");
    cout << *it << endl;
    return 0;
}