c++ - 解决外部库缺乏常量正确性的问题

标签 c++ compiler-errors const-correctness

我正在使用缺乏常量正确性的外部 C++ 库。假设我正在使用以下类的对象:

// Library.h
namespace Library {

class Message {
 public:
    std::string getData() {
        return data_;
    }
 private:
    std::string data_;
};

}  // namespace Library

请注意 getData() 返回一个拷贝,因此对该方法的调用不会更改 Message 对象,它应该是 const .但是,供应商决定不这样做。 在我这边的代码中,const 正确性很重要,Message 将在这样的函数中使用:

// MyApplication.cpp

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();
    // interprete and process content ...
}

有办法实现吗?换句话说,如何解决 error: passing 'const Library::Message' as 'this' argument discards qualifiers 错误 without changing the signature of the handleMessage 函数?

最佳答案

您还可以将包装器与可变成员变量一起使用,例如:

#include <string>

class Message {
 public:
    std::string getData() {
        return data_;
    }
    Message(std::string data): data_{data} { }
 private:
    std::string data_;
};

class MessageWrapper {
 public:
    MessageWrapper(Message message): message{message} {}
    std::string getData() const {
        return message.getData();
    }
 private:
    mutable Message message;
};

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();

}

int main() {
    MessageWrapper mw{{"abc"}};
    handleMessage(mw);
}

[live demo]

编辑:

为了强制 const 正确性,您可以保存一次从消息中检索到的数据,例如:

#include <string>
#include <optional>

class Message {
 public:
    std::string getData() {
        return data_;
    }
    Message(std::string data): data_{data} { }
 private:
    std::string data_;
};

class MessageWrapper {
 public:
    MessageWrapper(Message message): message{message} {}
    std::string getData() const {
        return (data)?(*data):(*(data = message.getData()));
    }
 private:
    mutable Message message;
    mutable std::optional<std::string> data;
};

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();

}

int main() {
    MessageWrapper mw{{"abc"}};
    handleMessage(mw);
}

[live demo]

关于c++ - 解决外部库缺乏常量正确性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215244/

相关文章:

c++ - 识别圈子

C++ -Weffc++ 警告与指针

Delphi注解+枚举集。不变的表达?

c++ - 如何从通过非常量输出参数提供所需数据的函数中获取替代值,以便为其分配对常量变量的引用?

c++ - 返回值的初始化应该忽略自动对象的常量性

基于成员存在的c++条件编译

c++ - 用 C++ 求解模方程组

C#条件运算符错误只有assignment,call,increment,decrement,await,new object expressions可以作为语句使用

c++ - const 正确性

c++ - 为什么我不必给函数数组的地址