简体   繁体   English

将类实例和方法作为参数传递给 C++ 中的另一个函数

[英]Passing class instance and method as argument to another function in C++

I have two classes.我有两节课。 One class has a method that takes a function as a parameter and that passed function is expected to have a string as an argument.一个类有一个将函数作为参数的方法,并且传递的函数应该有一个字符串作为参数。 For example:例如:

class Dog{
public:
    void doDogThings(std::function <void(std::string)> theFunction);

}

class Cat{
public:
    void doCatThings(std::string stringInput);
}

And here they are in action他们正在行动

int main(){
   Cat aCat;
   Dog aDog;
   std::string theString = "Oh jeez";
   aDog.doDogThings(<< insert cat's method and argument here >>);
   .....

This is the part that is fouling me up here;这是让我在这里犯规的部分; I know I should use我知道我应该使用

bind(&Cat::doCatThings, ref(aCat) ....?.....);

But I am stuck on how to pass the argument for the Cat method as a parameter to this function pointer.但是我坚持如何将 Cat 方法的参数作为参数传递给这个函数指针。 Any help would be greatly be appreciated.任何帮助将不胜感激。 Thanks.谢谢。

The correct bind syntax would be:正确的bind语法是:

aDog.doDogThings(std::bind(
    &Cat::doCatThings, std::ref(aCat), std::placeholders::_1));

The "placeholder" _1 means "the first argument to the resulting functor will get used here to pass to the bound callable". “占位符” _1表示“生成的函子的第一个参数将在此处用于传递给绑定的可调用对象”。

But I really don't recommend using std::bind in almost any circumstance.但我真的不建议在几乎任何情况下使用std::bind It has some annoying gotchas, is often tricky to get correct, tricky to read again after you've written a use of it, and results in the most terrible compiler errors any time you get something slightly wrong.它有一些烦人的问题,通常很难改正,在编写使用后再次阅读也很棘手,并且在任何时候出现轻微错误时都会导致最可怕的编译器错误。 Lambdas can do anything std::bind can do and quite a bit more, without most of those problems. Lambda 可以做任何std::bind可以做的事情,而且还可以做更多,而没有大多数这些问题。

So instead, I'd suggest:所以相反,我建议:

aDog.doDogThings(
    [&aCat](std::string stringInput)
    { aCat.doCatThings(std::move(stringInput)); }
);

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

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