I’m trying to use boost::regex_replace with a custom formatter. I need to pass a method from an object because some member is needed in the replacing function.
The signature of my replacing method is:
std::string MyObject::ReplaceStr(
boost::match_results<std::string::const_iterator> match) const
When calling regex_replace, I pass these arguments:
std::string replaced = regex_replace(
orig_string, replace_pattern,
boost::bind<std::string>(&MyObject::ReplaceStr, this, _1));
The problem is when regex_replace calls the format method on the match result, the Functor used is the one taking 3 parameters(Custom formatter can be string, unary, binary or ternary function). I think it is due to the fact that boost::bind somewhat hides arity of a function.
The reason why I think it is due the the arity disappearing is because when binding with
std::string replaced = regex_replace(
orig_string, replace_pattern,
std::bind1st(std::mem_fun(&MyObject::ReplaceStr), this));
the right functor(the one using the unary function) is called.
I could also probably just use a ternary function in my object to bind to and then it would probably work but for the sake of understanding and using boost::bind can someone explain if I understood correctly and if not provide the right explanation.
Bonus point if I can make it work with boost bind.
EDIT: I forgot to tell that it crashes when I use boost::bind due to selecting the wrong method signature. Here’s a code snippet to reproduce the behavior I tried to explain:
using namespace std;
using namespace boost;
class MyObject
{
public:
void ReplacePattern()
{
const std::string testString = "${value_to_replace}extra_value";
boost::regex replace_pattern("(\\$\\{(.*?)\\})");
std::string replaced = regex_replace(testString, replace_pattern, boost::bind(&MyObject::ReplaceStr, this, _1));
cout << "Replaced: " << replaced << endl;
}
std::string ReplaceStr(
boost::match_results<std::string::const_iterator> match) const
{
return "replaced_value";
}
};
int main(int argc, char* argv[])
{
MyObject obj;
obj.ReplacePattern();
char dummy[1];
cin.getline(dummy, 1);
return 0;
}
You could use boost::function to avoid ambiguity: