5

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?.

Community
  • 1
  • 1
Julien__
  • 1,962
  • 1
  • 15
  • 25

1 Answers1

2

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
David Stone
  • 26,872
  • 14
  • 68
  • 84
  • Thank you for your very good answer ! I learned a lot about meta-programming. Can we use it this way ? `FORWARDING_MEMBER_FUNCTIONS(std::decay::type, inner, function)` And with member pointer : `FORWARDING_MEMBER_FUNCTIONS(std::decay::type, *ptr, function);` ? – Julien__ Feb 09 '15 at 10:53
  • BTW, What prevents C++ from providing the same syntax `use inner.function;` for composition ? – Julien__ Feb 09 '15 at 11:00
  • @Julien__ You could change the macro to accept the type of the parameter. The downside is that you must then have your variable declaration occur before you invoke FORWARDING_MEMBER_FUNCTIONS, whereas if you specify the type explicitly, that restriction is not present. Which is better is up to you. You probably wouldn't want to use this with pointers, though, due to reference qualifiers. Nothing prevents C++ from using the using syntax to forward to functions of members, except that you'd have to convince the committee to accept it. – David Stone Feb 10 '15 at 14:50
  • @DavidStone Copying the code from the bitbucket repo and compiling over at [ideone](http://ideone.com/ZCMgUO) results in compilation error unless you comment out most of the FORWARDING_MEMBER_FUNCTION except for the one for reference... Compiling for msvc over at webcompiler.cloudapp.net was even more cryptic to me. I fail to understand what the use of the section starting from the second noexcept ... and onwards with the is_reference .. or is_nothrow.. – xerion Jun 25 '15 at 10:44
  • @xerion: Visual Studio is still pretty far behind in its C++14 conformance. The example code relies on constexpr, reference qualifiers for member functions, and automatic return type deduction for normal functions, none of which is supported until Visual Studio 2015 (which is not yet released). I do not know what version of gcc ideone is using for its compilation. When using anything in C++14, you'll want to be on the latest version of clang ideally, or at the very least the latest version of gcc. – David Stone Jun 25 '15 at 23:45
  • @xerion: The noexcept code is saying that your forwarding function is noexcept if everything that it calls is noexcept. It calls the function, and it also calls the move constructor of the return type, unless the return type is a reference. – David Stone Jun 25 '15 at 23:46
  • @DavidStone Aha I see, I thought that noexcept will set it to noexcept always. Also I now get it why the move constructor is needed but why constexpr? I was able to pass all the tests that you have over at your repo, without though being as optimized are you with the code below. `#define FORWARDING_MEMBER_FUNCTION(memberClass, object, function, qualifiers) \ template \ inline auto function(Args&&... args) qualifiers \ -> decltype(std::declval().function(std::declval()...)) \ { \ return (object).function(std::forward(args)...); \ }` – xerion Jun 26 '15 at 14:16