Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid this kind of repetition

Tags:

c++

c++11

dry

I have code similar to this:

#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";
};

I am wondering is there easy way to avoid code repetition in get() functions?

like image 532
Nick Avatar asked Sep 30 '16 09:09

Nick


2 Answers

wandbox example

Alternative to const_cast: creating a static template function that takes *this as a reference:

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);
    }
};

This works because of template argument deduction rules - in short, TSelf will accept both const and non-const references.

If you need to access members of this inside get_def_impl, use self.member.

Additionally, you can use std::conditional or similar facilities inside get_def_impl to do different things depending on the const-ness of TSelf. You can also use a forwarding reference (TSelf&&) and handle the case where this is being moved thanks to ref-qualifiers and perfect-forwarding.

like image 66
Vittorio Romeo Avatar answered Sep 30 '22 23:09

Vittorio Romeo


In some use cases you could also make use of non-member function template like:

#include <type_traits>
#include <string>

template <class U, class R = std::conditional_t<std::is_const<U>::value, std::string const&, std::string& >>
R get(U &u) {
   return u.s;
}

template <class U, class R = std::conditional_t<std::is_const<U>::value, std::string const&, std::string& >>
R get_def(U &u, typename std::remove_reference<R>::type& def) {
   return u.s.empty() ? u.s : def;
}

struct S {
   template <class U, class R>
   friend R get(U &);
   template <class U, class R>
   friend R get_def(U &, typename std::remove_reference<R>::type&);
private:
   std::string s;
};

int main() {
   S s;
   get(s) = "abc";
   //get(static_cast<const S &>(s)) = "abc"; // error: passing ‘const std::basic_string<char>’ as ‘this’...
   std::string s2 = get(static_cast<const S&>(s));
}
like image 33
W.F. Avatar answered Oct 01 '22 01:10

W.F.