user1899020
user1899020

Reputation: 13575

How to get the return type of a function with std::result_of?

I have a function quite complex

template<class E>
auto foo(E&& e);

And I want to get the return type by using

template<class E> using Foo = decltype(foo(E{}));

This cannot compile for E&& not okay.

I try using std::result_of many ways, but still failed. Any way to get the returned type?


Edit

The foo is

 template<class E>
 auto xt::strided_view(
     E &&e, 
     const xstrided_slice_vector &slices
 )

https://xtensor.readthedocs.io/en/latest/api/xstrided_view.html#namespacext_1aca6714111810062b91a1c9e31bd69b26

tried the following, does not work

    using E = xtensor<int, 2>;
    using SV = xt::xstrided_slice_vector;

    static_assert(is_same<
        invoke_result_t<decltype(xt::strided_view<E>), E, SV>,
        decltype(v)
    >::value);

    static_assert(is_same<
        decltype(xt::strided_view(declval<E>(), sv)),
        decltype(v)
    >::value);

showing

error C3556: 'xt::strided_view': incorrect argument to 'decltype'
 error C2955: 'std::is_same': use of class template requires template argument list

Upvotes: 1

Views: 1600

Answers (1)

JeJo
JeJo

Reputation: 32722

Any way to get the returned type?

You have either of the followings:

  1. using std::declval

    template<class E> using Foo = decltype(foo(std::declval<E>()));
    
  2. using std::invoke_result_t (since )

    template<class E> using Foo = std::invoke_result_t<decltype(foo<E>), E>;
    
  3. using decltype

    template<class E> using Foo = decltype(foo<E>(E{})); 
    

In which, the last one is really not recommended as E should be default constructed in the function call(i.e. foo<E>(E{})).


I tried using std::result_of many ways, but still failed.

Note that, std::result_of is deprecated in and (will be or already) removed from the standard in . Hence, trying to build something which standard does not support, is not a good idea (when you upgrade to newer standards in the future).

Upvotes: 2

Related Questions