Spec-Zone.ru › C++

std::result_of, std::invoke_result

Определено в заголовке <type_traits>
template< class >
class result_of; // not defined

template< class F, class... ArgTypes >
class result_of<F(ArgTypes...)>;
(1) (с C++11)
(устарело в C++17)
(удалено в C++20)
template< class F, class... ArgTypes >
class invoke_result;
(2) (с C++17)

Вычисляет тип возвращаемого значения выражения INVOKE во время компиляции.

F должно быть вызываемым типом, ссылкой на функцию или ссылкой на вызываемый тип. Вызов F с ArgTypes... должен быть корректным выражением.

(с C++11)
(до C++14)

F и все типы в ArgTypes могут быть любым полным типом, массивом неизвестной длины или (возможно, с квалификатором cv) void.

(с C++14)

Поведение программы, которая добавляет специализации для любого из шаблонов, описанных на этой странице, не определено.

Типы-члены

Тип-член Определение
type тип возвращаемого значения типа Callable F при вызове с аргументами ArgTypes.... Определяется только если F можно вызвать с аргументами ArgTypes... в контексте невычисления.(с C++14)

Вспомогательные типы

template< class T >
using result_of_t = typename result_of<T>::type;
(1) (с C++14)
(устарело в C++17)
(удалено в C++20)
template< class F, class... ArgTypes >
using invoke_result_t = typename invoke_result<F, ArgTypes...>::type;
(2) (с C++17)

Возможная реализация

namespace detail
{
    template<class T>
    struct is_reference_wrapper : std::false_type {};
    template<class U>
    struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {};
 
    template<class T>
    struct invoke_impl
    {
        template<class F, class... Args>
        static auto call(F&& f, Args&&... args)
            -> decltype(std::forward<F>(f)(std::forward<Args>(args)...));
    };
 
    template<class B, class MT>
    struct invoke_impl<MT B::*>
    {
        template<class T, class Td = typename std::decay<T>::type,
            class = typename std::enable_if<std::is_base_of<B, Td>::value>::type>
        static auto get(T&& t) -> T&&;
 
        template<class T, class Td = typename std::decay<T>::type,
            class = typename std::enable_if<is_reference_wrapper<Td>::value>::type>
        static auto get(T&& t) -> decltype(t.get());
 
        template<class T, class Td = typename std::decay<T>::type,
            class = typename std::enable_if<!std::is_base_of<B, Td>::value>::type,
            class = typename std::enable_if<!is_reference_wrapper<Td>::value>::type>
        static auto get(T&& t) -> decltype(*std::forward<T>(t));
 
        template<class T, class... Args, class MT1,
            class = typename std::enable_if<std::is_function<MT1>::value>::type>
        static auto call(MT1 B::*pmf, T&& t, Args&&... args)
            -> decltype((invoke_impl::get(
                std::forward<T>(t)).*pmf)(std::forward<Args>(args)...));
 
        template<class T>
        static auto call(MT B::*pmd, T&& t)
            -> decltype(invoke_impl::get(std::forward<T>(t)).*pmd);
    };
 
    template<class F, class... Args, class Fd = typename std::decay<F>::type>
    auto INVOKE(F&& f, Args&&... args)
        -> decltype(invoke_impl<Fd>::call(std::forward<F>(f),
            std::forward<Args>(args)...));
} // namespace detail
 
// Minimal C++11 implementation:
template<class> struct result_of;
template<class F, class... ArgTypes>
struct result_of<F(ArgTypes...)>
{
    using type = decltype(detail::INVOKE(std::declval<F>(), std::declval<ArgTypes>()...));
};
 
// Conforming C++14 implementation (is also a valid C++11 implementation):
namespace detail
{
    template<typename AlwaysVoid, typename, typename...>
    struct invoke_result {};
    template<typename F, typename...Args>
    struct invoke_result<
        decltype(void(detail::INVOKE(std::declval<F>(), std::declval<Args>()...))),
            F, Args...>
    {
        using type = decltype(detail::INVOKE(std::declval<F>(), std::declval<Args>()...));
    };
} // namespace detail
 
template<class> struct result_of;
template<class F, class... ArgTypes>
struct result_of<F(ArgTypes...)> : detail::invoke_result<void, F, ArgTypes...> {};
 
template<class F, class... ArgTypes>
struct invoke_result : detail::invoke_result<void, F, ArgTypes...> {};

Примечания

Как сформулировано в C++11, поведение std::result_of не определено, когда INVOKE(std::declval<F>(), std::declval<ArgTypes>()...) некорректно сформировано (например, когда F вообще не является вызываемым типом). C++14 изменяет это на SFINAE (если F не вызываемый, у std::result_of<F(ArgTypes...)> просто нет члена type).

Цель std::result_of — определить результат вызова Callable, особенно если этот тип результата отличается для разных наборов аргументов.

F(Args...) — это тип функции с Args... в качестве типов аргументов и F в качестве типа возвращаемого значения. В связи с этим std::result_of обладает несколькими особенностями, которые привели к его устареванию в пользу std::invoke_result в C++17:

  • F не может быть типом функции или массивом (но может быть ссылкой на них);
  • если любой из Args имеет тип «массив T» или тип функции T, он автоматически корректируется до T*;
  • ни F , ни какой-либо из Args... не может быть типом абстрактного класса;
  • если у любого из Args... есть квалификатор cv верхнего уровня, он отбрасывается;
  • ни один из Args... не может быть типа void.

Для избежания этих особенностей result_of часто используется с типами ссылок как F и Args.... Например:

template<class F, class... Args>
std::result_of_t<F&&(Args&&...)> // instead of std::result_of_t<F(Args...)>, which is wrong
    my_invoke(F&& f, Args&&... args)
    {
        /* implementation */
    }

Примечания

Макрос проверки наличия функции Значение Стандарт Функция
__cpp_lib_result_of_sfinae 201210L (C++14) std::result_of и SFINAE
__cpp_lib_is_invocable 201703L (C++17) std::is_invocable, std::invoke_result

Примеры

#include <iostream>
#include <type_traits>
 
struct S
{
    double operator()(char, int&);
    float operator()(int) { return 1.0; }
};
 
template<class T>
typename std::result_of<T(int)>::type f(T& t)
{
    std::cout << "overload of f for callable T\n";
    return t(0);
}
 
template<class T, class U>
int f(U u)
{
    std::cout << "overload of f for non-callable T\n";
    return u;
}
 
int main()
{
    // the result of invoking S with char and int& arguments is double
    std::result_of<S(char, int&)>::type d = 3.14; // d has type double
    static_assert(std::is_same<decltype(d), double>::value, "");
 
    // std::invoke_result uses different syntax (no parentheses)
    std::invoke_result<S,char,int&>::type b = 3.14;
    static_assert(std::is_same<decltype(b), double>::value, "");
 
    // the result of invoking S with int argument is float
    std::result_of<S(int)>::type x = 3.14; // x has type float
    static_assert(std::is_same<decltype(x), float>::value, "");
 
    // result_of can be used with a pointer to member function as follows
    struct C { double Func(char, int&); };
    std::result_of<decltype(&C::Func)(C, char, int&)>::type g = 3.14;
    static_assert(std::is_same<decltype(g), double>::value, "");
 
    f<C>(1); // may fail to compile in C++11; calls the non-callable overload in C++14
}

Вывод:

overload of f for non-callable T

См. также

invokeinvoke_r
(C++17)(C++23)
вызывает любой Callable-объект с заданными аргументами и возможностью указать тип возвращаемого значения(с C++23)
(шаблон функции)
is_invocableis_invocable_ris_nothrow_invocableis_nothrow_invocable_r
(C++17)
проверяет, может ли тип быть вызван (как если бы это было std::invoke ) с указанными типами аргументов
(шаблон класса)
declval
(C++11)
получает ссылку на свой аргумент для использования в контексте невычисления
(шаблон функции)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/types/result_of

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API