我经常听到很多关于c++中的函子。谁能给我一个概述,他们是什么,在什么情况下他们会有用?
当前回答
函子基本上就是一个定义操作符()的类。这让你可以创建“看起来像”函数的对象:
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
函子有几个优点。其一,与常规函数不同,它们可以包含状态。上面的例子创建了一个函数,无论你给它什么,它都会加上42。但是值42并不是硬编码的,它是在创建函数实例时作为构造函数参数指定的。我可以创建另一个加法器,只需要用不同的值调用构造函数,就可以加27。这使得它们可以很好地定制。
As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform should call. It should call add_x::operator(). That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.
如果我传递的是一个函数指针,编译器不能立即看到它指向哪个函数,所以除非它执行一些相当复杂的全局优化,否则它必须在运行时解除对指针的引用,然后进行调用。
其他回答
这是一个我被迫使用Functor来解决我的问题的实际情况:
我有一组函数(比如20个),它们都是相同的,除了每个函数在3个特定位置调用不同的特定函数。
这是难以置信的浪费和代码复制。通常我会传入一个函数指针,然后在3个位置调用它。(所以代码只需要出现一次,而不是20次。)
但后来我意识到,在每种情况下,特定的功能需要完全不同的参数配置文件!有时2个参数,有时5个参数,等等。
另一种解决方案是有一个基类,其中特定的函数是派生类中的重写方法。但是我真的想要构建所有这些INHERITANCE,只是为了传递一个函数指针????
解决方案:所以我所做的是,我做了一个包装类(一个“Functor”),它能够调用任何我需要调用的函数。我提前设置了它(用它的参数等),然后我传递它而不是函数指针。现在调用的代码可以触发Functor,而不知道内部发生了什么。它甚至可以多次调用它(我需要它调用3次)。
这就是一个实际的例子,在这个例子中,Functor被证明是一个明显而简单的解决方案,它允许我将代码重复从20个函数减少到1个。
小之外。你可以使用boost::function从函数和方法中创建函子,如下所示:
class Foo
{
public:
void operator () (int i) { printf("Foo %d", i); }
};
void Bar(int i) { printf("Bar %d", i); }
Foo foo;
boost::function<void (int)> f(foo);//wrap functor
f(1);//prints "Foo 1"
boost::function<void (int)> b(&Bar);//wrap normal function
b(1);//prints "Bar 1"
你可以使用boost::bind为这个函子添加状态
boost::function<void ()> f1 = boost::bind(foo, 2);
f1();//no more argument, function argument stored in f1
//and this print "Foo 2" (:
//and normal function
boost::function<void ()> b1 = boost::bind(&Bar, 2);
b1();// print "Bar 2"
最有用的是,使用boost::bind和boost::function,你可以从类方法创建函子函数,实际上这是一个委托:
class SomeClass
{
std::string state_;
public:
SomeClass(const char* s) : state_(s) {}
void method( std::string param )
{
std::cout << state_ << param << std::endl;
}
};
SomeClass *inst = new SomeClass("Hi, i am ");
boost::function< void (std::string) > callback;
callback = boost::bind(&SomeClass::method, inst, _1);//create delegate
//_1 is a placeholder it holds plase for parameter
callback("useless");//prints "Hi, i am useless"
你可以创建函子的列表或向量
std::list< boost::function<void (EventArg e)> > events;
//add some events
....
//call them
std::for_each(
events.begin(), events.end(),
boost::bind( boost::apply<void>(), _1, e));
所有这些东西都有一个问题,编译器错误消息不是人类可读的:)
函子是一个类似于函数的对象。 基本上,一个定义operator()的类。
class MyFunctor
{
public:
int operator()(int x) { return x * 2;}
}
MyFunctor doubler;
int x = doubler(5);
真正的优点是函子可以保存状态。
class Matcher
{
int target;
public:
Matcher(int m) : target(m) {}
bool operator()(int x) { return x == target;}
}
Matcher Is5(5);
if (Is5(n)) // same as if (n == 5)
{ ....}
在gtkmm中使用函子将一些GUI按钮连接到实际的c++函数或方法。
如果你使用pthread库使你的应用程序多线程,Functors可以帮助你。 要启动一个线程,pthread_create(..)的参数之一是要在自己的线程上执行的函数指针。 但有一个不便之处。这个指针不能是指向方法的指针,除非它是一个静态方法,或者除非你指定了它的类,比如class::method。还有一件事,你方法的接口只能是:
void* method(void* something)
因此,如果不做一些额外的事情,你就不能(以一种简单明显的方式)在线程中运行你的类中的方法。
在c++中处理线程的一个很好的方法是创建你自己的Thread类。如果你想运行MyClass类的方法,我所做的是,把那些方法转换成Functor派生类。
同样,Thread类有这样的方法: 静态void* startThread(void*参数) 指向该方法的指针将用作调用pthread_create(..)的参数。startThread(..)在arg中应该接收到的是一个void*类型的引用,它指向任何Functor派生类的堆中的实例,在执行时将被强制转换回Functor*,然后调用它的run()方法。
函子基本上就是一个定义操作符()的类。这让你可以创建“看起来像”函数的对象:
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
函子有几个优点。其一,与常规函数不同,它们可以包含状态。上面的例子创建了一个函数,无论你给它什么,它都会加上42。但是值42并不是硬编码的,它是在创建函数实例时作为构造函数参数指定的。我可以创建另一个加法器,只需要用不同的值调用构造函数,就可以加27。这使得它们可以很好地定制。
As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform should call. It should call add_x::operator(). That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.
如果我传递的是一个函数指针,编译器不能立即看到它指向哪个函数,所以除非它执行一些相当复杂的全局优化,否则它必须在运行时解除对指针的引用,然后进行调用。
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?
- 空括号的默认构造函数