我有类似的代码:
#include <string> class A{ public: std::string &get(){ return s; } const std::string &get() const{ return s; } std::string &get_def(std::string &def){ return ! s.empty() ? s : def; } // I kNow this might return temporary const std::string &get_def(const std::string &def) const{ return ! s.empty() ? s : def; } private: std::string s = "Hello"; };
解决方法
wandbox example
替代const_cast:创建一个静态模板函数,将*作为参考:
class A { private: template <typename TSelf,typename TStr> static auto& get_def_impl(TSelf& self,TStr& def) { return !self.s.empty() ? self.s : def; } public: auto& get_def(std::string& str) { return get_def_impl(*this,str); } const auto& get_def(const std::string& str) const { return get_def_impl(*this,str); } };
这是因为template argument deduction rules – 简而言之,TSelf将接受const和非const引用.
如果您需要访问get_def_impl内的成员,请使用self.member.
此外,您可以使用get_def_impl中的std ::条件或类似功能根据TSelf的常量来执行不同的操作.您还可以使用转发参考(TSelf&&&),并处理由于ref-qualifiers和perfect-forwarding而被移动的情况.
原文地址:https://www.jb51.cc/c/114814.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。