将匿名函数对象传递给std :: function? [英] Pass anonymous function object to std::function?

查看:694
本文介绍了将匿名函数对象传递给std :: function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的问题:
我定义一个函子:

Here is my question: I define a functor:

class A { 
 public: 
   int operator()(int a, int b) const{
    return a + b;
   }
 };
typedef function<int (int, int)> Fun;

那么我使用匿名函数创建一个std :: function对象,这是我的代码:

then I use a anonymous functor to create a std::function object, and I find something strange. Here is my code:

Fun f(A());
f(3, 4);

不幸的是错了。错误消息是:

Unfortunately it is wrong. The error message is:

error: invalid conversion from ‘int’ to ‘A (*)()’ [-fpermissive]
error: too many arguments to function ‘Fun f(A (*)())’

但是,当我改变我的代码如下:

However, when I change my code as follow:

A a;
Fun f(a);
f(3, 4);

Fun f = A();
f(3, 4);

结果是正确的。
那么,为什么呢?请帮助我理解它。感谢。

The result is right. So, why is it? Help me understand it,please. Thanks.

推荐答案

Fun f(A());

这是最讨厌的解析。它声明一个函数 f ,它返回一个 Fun 。它接受一个函数指针作为参数,指向一个不带参数的函数,并返回一个 A

This is a case of the most-vexing parse. It declares a function f which returns a Fun. It takes a function pointer as an argument, pointing at a function that takes no arguments and returns an A.

有几种方法可以解决这个问题:

There are a few ways to get around this:

Fun f{A()};    // Uniform-initialisation syntax
Fun f{A{}};    // Uniform-initialisation on both objects
Fun f((A()));  // Forcing the initialiser to be an expression, not parameter list

这篇关于将匿名函数对象传递给std :: function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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