使用boost bind将自定义格式化程序提升为只接受一个参数的方法

时间:2010-11-11 16:19:22

标签: c++ regex boost bind

我正在尝试将boost :: regex_replace与自定义格式化程序一起使用。我需要从对象传递一个方法,因为在替换函数中需要一些成员。

我的替换方法的签名是:

std::string MyObject::ReplaceStr(
    boost::match_results<std::string::const_iterator> match) const

调用regex_replace时,我传递了这些参数:

std::string replaced = regex_replace(
    orig_string, replace_pattern, 
    boost::bind<std::string>(&MyObject::ReplaceStr, this, _1));

问题是当regex_replace在匹配结果上调用format方法时,使用的Functor是3个参数(自定义格式化程序可以是字符串,一元,二元或三元函数)。我认为这是因为boost :: bind有点隐藏了一个函数的arity。

我认为这是因为arity消失的原因是因为与

绑定时
std::string replaced = regex_replace(
    orig_string, replace_pattern,       
    std::bind1st(std::mem_fun(&MyObject::ReplaceStr), this));

调用正确的函子(使用一元函数的函数)。

我也可能只是在我的对象中使用三元函数来绑定,然后它可能会起作用但是为了理解和使用boost :: bind有人可以解释我是否正确理解并且如果没有提供正确的解释

如果我可以使用boost bind工作,那么可以获得奖励。

编辑:由于选择了错误的方法签名,我忘了告诉它在使用boost::bind时崩溃了。这是一个代码片段,用于重现我试图解释的行为:

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;
}

1 个答案:

答案 0 :(得分:2)

你可以使用boost :: function来避免含糊不清:

boost::function<std::string (boost::match_results<std::string::const_iterator>)> function =
    boost::bind(&MyObject::ReplaceStr, this, _1);
std::string replaced = regex_replace(testString, replace_pattern, function);