获取C ++中返回值的类型 [英] Get the type of the return value in C++
本文介绍了获取C ++中返回值的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个函数 f
,该函数返回某个未知类型的值(我们称它为 T
),接受 T
类型的值作为参数(可能还有其他一些参数)。如何在C ++ 14中获得 f
的返回类型?
Suppose we have a function f
which returns a value of some unknown type (let's call it T
) and takes a value of the type T
as an argument (and possibly has some other arguments). How do I get the return type of f
in C++14?
有一种方法可以做到如果我们知道参数类型(通过 std :: result_of
)。是否可以知道除 T
以外的所有参数类型?
There is a way to do it if we know the know the argument types (via std::result_of
). Is it possible if we know all the argument types except T
?
示例:
template <class F> // F is functor with T operator()(T a, T b)
class A {
// Here I want to do
// T some_function(T some_arg) { ... }
}
推荐答案
template <typename T>
struct return_type;
template <typename R, typename... Args>
struct return_type<R(Args...)> { using type = R; };
template <typename R, typename... Args>
struct return_type<R(*)(Args...)> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...)> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) &> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) &&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const&&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile&&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile&&> { using type = R; };
template <typename T>
using return_type_t = typename return_type<T>::type;
测试:
#include <type_traits>
struct Functor
{
int operator()(int i, int j) { return i + j; }
};
template <class F>
struct A
{
using T = return_type_t<decltype(&F::operator())>;
T some_function(T some_arg) { return some_arg; }
};
int main()
{
A<Functor> a;
static_assert(std::is_same<decltype(a.some_function(1)), int>::value, "!");
}
这篇关于获取C ++中返回值的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文