Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

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

    string& get(double d){
        cout << "Used :const not called...
";
        return m;
    }
    const string& get(double d) const{
        cout << "Used :const called...
";
        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...
";
    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...
";
    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?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...