【问题标题】:C++ string.replace generates "No matching function for call" errorC++ string.replace 生成“No matching function for call”错误
【发布时间】:2018-04-03 15:44:32
【问题描述】:

谁能告诉我为什么这段代码会产生“No matching function for call”错误?我相信语法是正确的,我真的不知道为什么它不起作用。我想用传递给函数的 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_;
}

View 类看起来就这么简单:

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

完整的错误是:

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

【问题讨论】:

标签: c++ string class object


【解决方案1】:

你的函数定义为

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

因为它是const,这意味着你不能修改任何类成员。 replace 会修改 Template_ 所以你不能调用它。

您有两种方法可以解决此问题。如果您希望能够操作Template,则可以去掉函数上的const,或者您可以将Template_ 声明为mutable,以便对其进行修改。

【讨论】:

  • 或者使用初始化为Template_的局部变量并修改并返回。
  • 谢谢。我完全忘记了。现在完美运行。
【解决方案2】:

问题是由于试图修改 const 对象的成员变量引起的。

成员函数是const 成员函数。因此,this-&gt;Template_ 也是一个 const 对象。您正在尝试使用修改this-&gt;Template_

this->Template_.replace(PositionBegin, Key.length()+4, Found->second);

如果您的程序逻辑要求您在 const 成员函数中修改 this-&gt;Template_,则必须使用 mutable 对其进行限定。

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2020-11-08
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2019-05-07
    • 2014-10-08
    相关资源
    最近更新 更多