c – 如何避免这种重复
发布时间:2020-12-16 05:27:07 所属栏目:百科 来源:网络整理
导读:我有类似的代码: #include stringclass 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
我有类似的代码:
#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"; }; 我想知道有没有办法避免在代码重复的get()函数? 解决方法
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而被移动的情况. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |