如何获取std::result_of函数的返回类型

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

本文关键字:result of 函数 返回类型 std 何获取 获取      更新时间:2023-10-16

我有一个相当复杂的函数

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

我想通过使用获得返回类型

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

这无法为E&amp;不好。

我尝试了很多方法使用std::result_of,但还是失败了。有办法得到返回的类型吗?


编辑

foo

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

尝试了以下操作,不起作用

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);

显示

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

有什么方法可以获得返回的类型吗?

您有以下任一项:

  1. 使用std::declval

    template<class E> using Foo = decltype(foo(std::declval<E>()));
    
  2. 使用std::invoke_result_t(自c+++17起(

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

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

其中,最后一个确实不推荐使用,因为E应该在函数调用中默认构造(即foo<E>(E{})(。


我尝试了很多方法使用std::result_of,但仍然失败了。

请注意,std::result_of在c++17中已弃用,并且(将或已经(从c++20中的标准中删除。因此,尝试构建标准不支持的东西不是一个好主意(当您将来升级到较新的标准时(。