c++ - 如何避免这种重复

标签 c++ c++11 dry

我有类似的代码:

#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 : 创建一个 static采用 *this 的模板函数作为引用:

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引用。

如果你需要访问this的成员里面get_def_impl , 使用 self.member .

此外,您可以使用 std::conditional或内部类似设施 get_def_impl根据 const 做不同的事情-性 TSelf .您还可以使用转发引用 ( TSelf&& ) 并处理 this 的情况由于ref-qualifiers而被移动和 perfect-forwarding .

关于c++ - 如何避免这种重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787837/

相关文章:

ruby-on-rails - 将类和方法调用传递给要在 Ruby 中使用的方法

javascript - 使此 JavaScript 代码变干的最优雅的方法

c++ - 如何在 cpp 中出现 "ignore"段错误?

c++ - 使用 "()"调用构造函数不同于 "{}"

c++ - 如何将使用默认参数的函数传递给 std::thread?

c++ - 在与 initializer_list 不兼容的 C++ 模板复制赋值运算符中?

java - 如何重构这段代码?

c++ - QT : webkit webkitwidgets creating a click package on Ubuntu 中的未知模块

c++ - Boost fusion as_map转换行为

c++ - void f(int) 的模板和 decltype