如何避免这种重复

Nic*_*ick 10 c++ dry c++11

我有类似这样的代码:

#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";
};
Run Code Online (Sandbox Code Playgroud)

我想知道是否有简单的方法来避免get()函数中的代码重复?

Vit*_*meo 13

wandbox示例

替代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);
    }
};
Run Code Online (Sandbox Code Playgroud)

这是因为模板参数推导规则 - 简而言之,TSelf将接受两个const和非const引用.

如果您需要访问this内部成员get_def_impl,请使用self.member.

此外,还可以使用std::conditional或内类似设施get_def_impl做取决于不同的事情const的-ness TSelf.您还可以使用转发引用(TSelf&&)并处理this由于引用限定符完美转发而移动的情况.