为什么std :: result_of <int(int)> :: type有效?

R S*_*ahu 8 c++ c++11

我已阅读以下相关问题:

  1. std :: result_of简单函数
  2. decltype,result_of或typeof?

cppreference.com 上的页面std::result_of.

所有这些似乎表明我应该能够使用:

 std::result_of<int(int)>::type v1 = 10;
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用g ++ 4.9.2构建以下程序时

#include <type_traits>

int foo()
{
   return 0;
}

int main()
{
    std::result_of<int(int)>::type v1 = 10;           // LINE A
    std::result_of<decltype(foo)>::type v2 = 20;      // LINE B
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到"LINE A"和"LINE B"的错误消息.错误消息是:

socc.cc: In function ‘int main()’:
socc.cc:10:5: error: ‘type’ is not a member of ‘std::result_of<int(int)>’
     std::result_of<int(int)>::type v1 = 10;
     ^
socc.cc:11:5: error: ‘type’ is not a member of ‘std::result_of<int()>’
     std::result_of<decltype(foo)>::type v2 = 20;
     ^
Run Code Online (Sandbox Code Playgroud)

我用来编译的命令:

g++ -std=c++11 -Wall    socc.cc   -o socc
Run Code Online (Sandbox Code Playgroud)

FWIW,使用

 typename std::result_of<int(int)>::type v1 = 10;
 typename std::result_of<decltype(foo)>::type v2 = 20;
Run Code Online (Sandbox Code Playgroud)

没有什么区别.

似乎我无法理解result_of应该如何使用.

你能解释一下为什么我会收到编译错误吗?

lis*_*rus 12

您似乎假设std::result_of<R(Args...)>::type只是R- 也就是说,具有签名的函数的结果类型R(Args...).但是std::result_of<F(Args...)>::type调用带有类型F参数的类型实例的结果Args....

所以,std::result_of<int(int)>::type没有意义 - int对象不可调用.

请再次阅读cppreference :)


Meh*_*olf 11

如您已发布的链接中所述,参数的第一部分result_of必须是可调用类型或对函数的引用.

假设你有一个

struct Callable
{
    int operator()(double);
    void operator()(int);
};
Run Code Online (Sandbox Code Playgroud)

result_of如果你知道参数的类型,那么可以帮助你确定返回类型.对于上面的例子:

result_of<Callable(int)>::type == void    ... per definition
result_of<Callable(double)>::type == int  ... per definition
result_of<Callable(char)>::type == void   ... the int-overload matches better
result_of<Callable(float)>::type == int   ... the double-overload matches better
Run Code Online (Sandbox Code Playgroud)

为了找到函数的返回类型,foo您必须通过函数引用:

result_of<decltype(foo)& ()>::type == int
Run Code Online (Sandbox Code Playgroud)

但这似乎有点扭曲,因为你可以直接写

decltype(foo()) == int
Run Code Online (Sandbox Code Playgroud)