Julien__ Julien__ - 4 years ago 132
C++ Question

Method forwarding with composition instead of inheritance (using C++ traits)

I would like to use composition and to write good forwarding methods for every possible overload (noexcept, const, volatile) using C++ capabilities.

The idea is to use traits in order to determine whether a method is declared {noexcept / const / volatile / etc.} and to behave accordingly.

Here is an example of what I would like to achieve :

struct User{
UsedObject& obj;
User(UsedObject& obj) : obj(obj) {}

FORWARD_METHOD(obj, get); //here is where the forwarding happens
};

struct UsedObject{
string m{"Hello\n"};

string& get(double d){
cout << "\tUsed :const not called...\n";
return m;
}
const string& get(double d) const{
cout << "\tUsed :const called...\n";
return m;
}
};


Here is what I have so far** :

// forward with noexcept attribute
// I'm not 100% sure about : std::declval<std::add_lvalue_reference<decltype(obj)>::type

template<typename... Args>
constexpr decltype(auto) get(Args && ... args)
noexcept(
noexcept(std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get( std::forward<Args>(args)... ))
and
std::is_nothrow_move_constructible<decltype( std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get( std::forward<Args>(args)... ) )>::value
)
{
cout << "const called...\n";
return obj.get(std::forward<Args>(args)...);
}

// forward with noexcept and const attributes
// I'm not sure that this one behave properly.

template<typename... Args>
constexpr decltype(auto) get(Args && ... args)
const noexcept(
noexcept(std::declval< std::add_const<decltype(obj) &>::type >().get( std::forward<Args>(args)... ))
and
std::is_nothrow_move_constructible<decltype( std::declval< std::add_const<decltype(obj) &>::type >().get( std::forward<Args>(args)... ) )>::value
)
{
cout << "const not called...\n";
using const_type = std::add_lvalue_reference<std::add_const<std::remove_reference<decltype(obj)>::type>::type>::type;
return const_cast<const_type>(obj).get(std::forward<Args>(args)...);
}


Please note that this question is different from the following one, because I know that we can use c++ traits in order to inspect an object interface : Composition: using traits to avoid forwarding functions?

** inspired by a thread of comments with @David Stone here : When should I use C++ private inheritance?.

Answer Source

Let's start with the solution and explain it piece by piece.

#define FORWARDING_MEMBER_FUNCTION(Inner, inner, function, qualifiers) \
    template< \
        typename... Args, \
        typename return_type = decltype(std::declval<Inner qualifiers>().function(std::declval<Args &&>()...)) \
    > \
    constexpr decltype(auto) function(Args && ... args) qualifiers noexcept( \
        noexcept(std::declval<Inner qualifiers>().function(std::forward<Args>(args)...)) and \
        ( \
            std::is_reference<return_type>::value or \
            std::is_nothrow_move_constructible<return_type>::value \
        ) \
    ) { \
        return static_cast<Inner qualifiers>(inner).function(std::forward<Args>(args)...); \
    }

#define FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, const reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, volatile reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, const volatile reference)

#define FORWARDING_MEMBER_FUNCTIONS(Inner, inner, function) \
    FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, &) \
    FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, &&)

Inner represents the type of the object you are forwarding to, and inner represents its name. Qualifiers is the combination of const, volatile, &, and && that you need on your member function.

The noexcept specification is surprisingly complicated just because you need to handle the function call as well as constructing the return value. If the function you are forwarding returns a reference, you know it is safe (references are always noexcept constructible from the same type), but if the function returned by value, you need to make sure that object's move constructor is noexcept.

We were able to simplify this a little bit by using a defaulted template argument return_type, otherwise we would have had to spell out that return type twice.

We use the static_cast in the body of the function to handle properly adding cv and reference qualifiers to the contained type. This is not automatically picked up by reference qualifiers on the function.

Using inheritance instead of composition

Using private inheritance, the solution looks more like this:

struct Outer : private Inner {
    using Inner::f;
};

This has the advantage of

  • Readability
  • Faster compile times
  • Faster code in debug builds (nothing to inline)
  • Not using up your constexpr recursion depth
  • Not using up your template instantiation depth
  • Working with returning non-movable types by value
  • Working with forwarding to constructors
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download