C ++ string.replace生成“没有匹配的调用函数”错误

Baz*_*nia 0 c++ string class object

谁能告诉我为什么这段代码生成“没有匹配的调用函数”错误?我相信语法是正确的,我真的不知道为什么它不起作用。我想用传递给函数的unordered_map中some_key的匹配值替换Template_中{{some_key}}的出现。

std::string View::Render(const std::unordered_map<std::string, std::string> &model) const {

    for(int i = 0; i < this->Template_.length(); ++i){
        if(this->Template_[i] == '{' && this->Template_[i+1] == '{'){

            int PositionBegin = i;
            std::string Key = FindKey();

            if(Key.length() > 0) {
                std::unordered_map<std::string, std::string>::const_iterator Found = model.find(Key);
                if (Found != model.end())
                    this->Template_.replace(PositionBegin, Key.length()+4, Found->second);
            }
        }
    }

    return this->Template_;
}
Run Code Online (Sandbox Code Playgroud)

视图类看起来像这样简单:

class View {
public:
    View(const std::string &Template);
    std::string Render(const std::unordered_map<std::string, std::string> &model) const;
    std::string Template_;
};
Run Code Online (Sandbox Code Playgroud)

完整的错误是:

error: no matching function for call to ‘std::__cxx11::basic_string<char>::replace(int&, std::__cxx11::basic_string<char>::size_type, const std::__cxx11::basic_string<char>&) const’ this->Template_.replace(PositionBegin, Key.length()+4, Found->second);
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 5

您的功能定义为

std::string View::Render(const std::unordered_map<std::string, std::string> &model) const
Run Code Online (Sandbox Code Playgroud)

因为这const意味着您不能修改任何类成员。 replace会进行修改,Template_因此您无法调用它。

您有两种方法可以解决此问题。const如果您希望能够进行操作,则可以删除该函数上的on,Template也可以声明Template_为as mutable以便对其进行修改。