关于std :: result_of在c ++ 11 [英] about std::result_of in c++11

查看:275
本文介绍了关于std :: result_of在c ++ 11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道, std :: result_of 的可能实现是

template<class F, class... ArgTypes>
struct result_of<F(ArgTypes...)>
{
    typedef decltype(
        std::declval<F>()(std::declval<ArgTypes>()...)
        ) type;
};

但是当我使用 std :: result_of 我有一些麻烦。

But when I use std::result_of I have some trouble.

int f(int x)
{
    return 0;
}

template<typename T>    
void Test(const T& t)
{
    decltype(std::declval<T>()(std::declval<int>())) i1 = 1; // ok
    typename std::result_of<T(int)>::type i2 = 2; // compile error:
    // function returning a function
    // I think this means the same thing just as above, right?
}

int main()
{
    Test(f);
    return 0;
}

这两种形式有什么区别?

What are the differences between these two forms?

推荐答案

std :: result_of 在C ++ 11中声明[meta.trans.other] 57 as:

std::result_of is declared in C++11 [meta.trans.other] Table 57 as:

template <class Fn, class... ArgTypes> struct result_of<Fn(ArgTypes...)>;

并且它要求:


Fn 应为可调用类型(20.8.1),引用函数或引用可调用类型。表达式

Fn shall be a callable type (20.8.1), reference to function, or reference to callable type. The expression

decltype(INVOKE(declval<Fn>(), declval<ArgTypes>()...))

必须完善。

在[func.def] / 3中定义:

callable type is defined in [func.def]/3:


> callable type 是一个函数对象类型(20.8)或指向成员的指针。

A callable type is a function object type (20.8) or a pointer to member.

是在[function.objects] / 1中定义的:

function object type is defined in [function.objects]/1:


对象类型(3.9),它可以是函数调用(5.2.2,13.3.1.1)中的 postfix-expression 类型。 ...

在程序中, f int(int),因此 T 被推导到函数类型 int )。请注意,函数类型不是 Fn 要传递给 std :: result_type的有效选项之一。但是,对函数的引用是一种可接受的类型:您应该将 Test s的完整类型参数传递给 result_of 而不是只有 T Demo at Coliru ):

In your program, f is a reference to a function of type int(int), so T is deduced to the function type int(int). Note that a function type is not one of the valid options for the type Fn to be passed to std::result_type. A reference to function is an acceptable type, however: you should pass the full type of Tests parameter to result_of instead of only T (Demo at Coliru):

template<typename T>    
void Test(const T&)
{
    decltype(std::declval<T>()(std::declval<int>())) i1 = 1;
    typename std::result_of<const T& (int)>::type i2 = 2;
}

关于这两种表单之间的区别,请记住 std :: declval 始终返回引用类型;特别是 std :: declval< T>()返回 T&&

Regarding the difference between the two forms, remember that std::declval always returns a reference type; specifically std::declval<T>() returns T&&. So

decltype(std::declval<T>()(std::declval<int>()))

要求在 T&& 使用 int&&& 参数调用。

这篇关于关于std :: result_of在c ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆