简体   繁体   中英

Backport C++14 return type deduction to C++11

How can I make this code c++11 compliant?

template <class ...Args>
auto operator()(Args&&... args) const
{
    return _delegate(std::forward<Args>(args)...);
}

The code is part of a templated struct. _delegate is a member and defined like below.

/// The implementation of the slot, as a delegate.  
typedef fastdelegate::FastDelegate<Signature> impl_delegate;    
impl_delegate _delegate;

The complete files can be found here. It is the slot.hpp. https://github.com/miguelmartin75/Wink-Signals/tree/master/wink

You can simply add a trailing return type :

template <class ...Args>
auto operator()(Args&&... args) const
    -> decltype(_delegate(std::forward<Args>(args)...))
{
    return _delegate(std::forward<Args>(args)...);
}

live wandbox example

If your compiler is complaining about _delegate in the trailing return type , try using std::declval</* type of '_delegate' */>() instead.


Note that the code above might behave differently from the C++14 one. Consider the case where it's overloaded with the following member function:

auto operator()(...) const { }

In C++14, automatic return type deduction is not SFINAE-friendly, so the original function in the question will probably cause an hard compilation error if _delegate(std::forward<Args>(args)...) is ill-formed instead of SFINAE-ing away.

In C++11, _delegate(std::forward<Args>(args)...) is part of the signature - if it is ill-formed, other overloads will have a chance to be selected.

Here's a live example on wandbox . Uncomment line 15 to see the changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM