boost.png (6897 bytes) Home Libraries People FAQ More

Binders 綁定器

The header functional.hpp provides enhanced versions of both the binder function object adapters from the C++ Standard Library (§20.3.6):

頭文件 functional.hpp 為C++標準庫(§20.3.6)中的以下綁定器函數對像提供了增強版本:

As well as the corresponding helper functions

以及以下相應輔助函數:

The key benefit of these adapters over those in the Standard Library is they avoid the problem of references to references.

與標準庫中的相應適配器相比,這些適配器的主要優點是避免了 "到引用的引用" 的問題。

Usage 用法

Usage is identical to the standard binders. For example,

使用的方法與標準庫一樣。例如:

class Foo {
public:
void bar(std::ostream &);
// ...
};
// ...
std::vector<Foo> c;
// ...
std::for_each(c.begin(), c.end(),
boost::bind2nd(boost::mem_fun_ref(&Foo::bar), std::cout));

References to References 到引用的引用

Consider the usage example above

考慮前面的用法示例:

class Foo {
public:
void bar(std::ostream &);
// ...
};
// ...
std::for_each(c.begin(), c.end(),
boost::bind2nd(boost::mem_fun_ref(&Foo::bar), std::cout));

If this had been written using std::bind2nd and std::mem_fun_ref, it would be unlikely to compile.

如果這個例子是用 std::bind2ndstd::mem_fun_ref 編寫的,它不太可能通過編譯。

The problem arises because bar takes a reference argument. The Standard defines std::mem_fun_ref such that it creates a function object whose second_argument_type will be std::ostream&.

問題是由於 bar 接受的是一個引用參數而引起的。按照標準中所定義的 std::mem_fun_ref,它將創建一個函數對象,其 second_argument_typestd::ostream&.

The call to bind2nd creates a binder2nd which the Standard defines as follows:

bind2nd 的調用將創建一個 binder2nd,按標準的定義如下:

template <class Operation>
class binder2nd
: public unary_function<typename Operation::first_argument_type,
typename Operation::result_type> {
...
public:
binder2nd(const Operation& x,
const typename Operation::second_argument_type& y);
...

Since our operation's second_argument_type is std::ostream&, the type of y in the constructor would be std::ostream&&. Since you cannot have a reference to a reference, at this point we should get a compilation error because references to references are illegal in C++ (but see C++ Standard core language active issues list).

由於我們所操作的 second_argument_typestd::ostream&, 所以在構造函數中,y 的類型就會是 std::ostream&&. 而你不可能擁有一個到引用的引用,到此我們將得到一個編譯錯誤,因為引用的引用在C++中是非法的(請見 C++ 標準核心語言活躍問題列表)。

The binders in this library avoid this problem by using the Boost call_traits templates.

本庫中的綁定器通過使用 Boost call_traits 模板,避免了這一問題。

Our constructor is declared

我們的構造函數聲明如下:

binder2nd(const Operation& x,
typename call_traits<
typename binary_traits<Operation>::second_argument_type
>::param_type y
)

As a result, y has a type of std::ostream&, and our example compiles.

這樣,y 的類型為 std::ostream&, 我們的例子就可以通過編譯了。


Valid HTML 4.01 Transitional

Revised 02 December, 2006

Copyright c 2000 Cadenza New Zealand Ltd.

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)