开发者

Binding member functions

In the example in member function section: Member functions We got a struct X:

struct X {
  int foo(int);
};

Preferred syntax

boost::function<int (X*, int)> f;

f = &X::foo;

X x;
f(&x, 5);

Portable syntax

boost::function2<int, X*, int> f;

f = &X::foo;

X x;
f(&x, 5);

My questions are:

  • Why do I have to put an additional X* argument when my int foo(int) only take one argument? Also, is that the same as using boost::bind, such as:

Person *per开发者_StackOverflowson = new Person("Tu", 23);

boost::function newFunc2 = boost::bind(&Person::printInfo,person);

  • What's the difference between prefer syntax and portable syntax and when to use one over another?
  • What is function object? Is that function pointer?


  1. Any member function has a pointer to the object to operate on implicitly set as its first parameter. When you have code like this: X x; x.foo(10); the compiler might really be calling foo(&x, 10) for you (see here for two ways this may be handled) - obviously, the name foo would have been mangled in some way.

  2. See the Boost documentation for a description of the syntaxes. Below is the most relevant extract from the page. Basically, you should use the preferred version if your compiler supports it, as its closest to the normal definition for a function pointer (readability) and uses fewer template arguments (faster compile times).

    Boost.Function has two syntactical forms: the preferred form and the portable form. The preferred form fits more closely with the C++ language and reduces the number of separate template parameters that need to be considered, often improving readability; however, the preferred form is not supported on all platforms due to compiler bugs. The compatible form will work on all compilers supported by Boost.Function. Consult the table below to determine which syntactic form to use for your compiler.

  3. A function pointer is a plain old pointer that happens to accept functions with a specific return type and argument list. A function object is any type that has an operator() defined - allowing it to be called as a function.


  1. You need to pass object of type X, because that is a member function pointer. You need an object on which you are calling that member function.

  2. portable syntax is for older and newer compilers, and prefered syntax can not compile on older compilers. The detail difference is explained at the functor tutorial page

  3. function object is such object which you can call as a function. It can be function pointer or member function pointer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜