我想做这样的事情:
boost::regex re("tryme");
ifstream iss;
iss.open("file.txt");
istream_iterator<string> eos;
istream_iterator<string> iit (iss);
find(iit,eos,bind2nd(boost::regex_match),re));
错误如下:
Could not find a match for 'bind2nd<_Fn2,_Ty>(bool (*) (BidiIterator,BidiIterator,match_results &,const basic_regex &,unsigned long))'
Could not find a match for 'find(istream_iterator,int>,istream_iterator,int>,undefined,regex)'
你能帮我正确地做一下吗?谢谢。
最佳答案
第一个问题是 std::find()
尝试匹配值,即,您需要将 std::find()
替换为 std::find_if()
。这很简单。
下一个问题是 boost::regex_match
不是一个函数,而是一系列函数。 std::bind2nd()
不知道您想要匹配该家族的哪个成员。此外,您显然想要使用的函数重载需要三个而不是两个参数:默认情况下类型为 boost::match_flag_type 的最后一个参数。我让它与 std::bind()
使用:
std::bind(static_cast<bool (*)(std::string const&,
boost::regex const&,
boost::match_flag_type)>(&boost::regex_match),
std::placeholders::_1, re);
如果您确实想使用std::bind2nd()
,创建一个简单的转发函数可能是最简单的:
bool my_regex_match(std::string s, boost::regex const& r) {
return boost::regex_match(s, r);
}
void f() {
boost::regex re("tryme");
std::ifstream iss(file.txt);
std::find_if(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::bind2nd(std::ptr_fun(&my_regex_match), re));
}
std::bind2nd()
模板无法真正使用原始函数指针。这就是需要使用 std::ptr_fun()
的原因。一般来说,当需要使用任何名为 *_fun()
的标准函数时,乐趣实际上就停止了:这些函数无法处理通过引用获取参数的函数。因此,my_regex_match()
按值获取其 std::string
参数:std::bind2nd()
会尝试创建一个函数对象,该函数对象采用否则,对引用的引用作为参数。这是您可能想要使用 std::bind()
或 boost::bind()
的另一个原因。
关于c++ - 使用 boost 在文件中查找正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772912/