代码之家  ›  专栏  ›  技术社区  ›  Eric Fortin

使用只使用一个参数的Boost绑定到方法来增强自定义格式化程序

  •  3
  • Eric Fortin  · 技术社区  · 14 年前

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

    我的替换方法的签名是:

    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对匹配结果调用格式方法时,使用的函数是采用3个参数的函数(自定义格式设置工具可以是字符串、一元、二进制或三元函数)。我认为这是因为boost::bind在某种程度上隐藏了函数的arity。

    我之所以认为是由于数量的消失,是因为当与

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

    调用右函数(使用一元函数的函数)。

    我也可以在我的对象中使用三元函数来绑定,然后它可能会工作,但是为了理解和使用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 回复  |  直到 14 年前
        1
  •  2
  •   chris    14 年前

    可以使用boost::函数来避免歧义:

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