简体   繁体   English

std :: tr1 ::功能分配和绑定

[英]std::tr1::function assignment and binding

I'm trying to learn how to best use the std::function and the std::bind facilities in the standard library - I'm interested in the TR1 versions, as that's what I have available for now and I'm not aware of the differences, if any, between the TR1 implementations and the C++11 ones. 我正在尝试学习如何最好地使用标准库中的std :: function和std :: bind工具-我对TR1版本感兴趣,因为这是我现在可以使用的功能,我不知道TR1实现和C ++ 11实现之间的差异(如果有)。

So for the sake of the exercise I've set up to construct a simple let's say "dispatcher". 因此,为了便于练习,我建立了一个简单的“调度程序”。 What I want is to be able to execute any function from the dispatcher based on some decisions taken later at runtime. 我想要的是能够根据稍后在运行时做出的一些决定,从调度程序执行任何功能。 I set up my class to have a general function data member like so: 我将类设置为具有通用函数数据成员,如下所示:

class PoorDispatcher
{
 ...
 private:
     std::tr1::function<void()> m_f;
}

Then I assign to the data member the function I really want to call, similar to the below 然后,我将要调用的函数分配给数据成员,类似于以下内容

...
m_f = std::tr1::bind(some_func, param1, param2, param3);
...
// then the call
m_f(); // SUCCESS

The above allows me to call successfully the function I want but I'm not sure it's the right thing to do. 上面的代码使我可以成功调用所需的函数,但是我不确定这是正确的事情。 The questions: 问题:

  1. Is the above usage scenario "sane"? 上面的使用场景是否“理智”? Are there any better alternatives? 有更好的选择吗?
  2. The above method poses a problem when trying to bind to a function which returns something. 当尝试绑定到返回某些内容的函数时,上述方法会带来问题。 How can I retrieve the return value? 如何获取返回值? (In my silliness I tired to cast the function objects without much success) (我很傻,我厌倦了在没有成功的情况下转换功能对象)

The template argument to std::function is the actual function type. std::function的模板参数是实际的函数类型。 void() means a function which takes no arguments and returns no value. void()表示一个不带参数也不返回值的函数。

If you want to store a function that returns a value you have to create a new function object. 如果要存储返回值的函数,则必须创建一个新的函数对象。 Or if you are not sure if the function will return something, use boost.optional . 或者,如果不确定函数是否会返回某些内容,请使用boost.optional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM