学用boost::bind

Posted on 2008-03-28 11:37 RichardHe 阅读(346) 评论(0)  编辑 收藏 引用
(1) 现在的类库最多可以支持9个参数。
(2)在绑定一个成员函数时,bind 表达式的第一个参数必须是成员函数所在类的实例!理解这个规则的最容易的方法是,这个显式的参数将取

替隐式的 this ,被传递给所有的非静态成员函数。细心的读者将会留意到,实际上这意味着对于成员函数的绑定器来说,只能支持八个参数

,因为第一个要用于传递实际的对象。
(3)当我们传递某种类型的实例给一个 bind 表达式时,它将被复制,除非我们显式地告诉 bind 不要复制它。要避免复制,我们必须告诉

bind 我们想传递引用而不是它所假定的传值。我们要用 boost::ref 和 boost::cref (分别用于引用和 const 引用)来做到这一点,它们也是

Boost.Bind 库的一部分。还有一种避免复制的方法;就是通过指针来传递参数而不是通过值来传递。

不然对象会被构造很多次.效率会降低很多,我已经实践过了.析构也会一样....代码如下:

class Trace
{
public:
    Trace() {std::cout<<"constructor!"<<endl;}
    Trace(const Trace& other)
    {
        std::cout<<"constructor by other!"<<endl;
    }
    Trace& operator =(const Trace& other)
    {
        std::cout <<"tracer& tracer::operator=(const tracer& other)\n";  
        return *this;
    }
    ~Trace(){std::cout << "tracer::~tracer()\n"; }
    void print(const std::string& s)const
    {
        std::cout << s << endl;
    }
};
void main()
{   
    Trace trace;
//Trace为类,trace为对象
    boost::bind(
&Trace::print,trace,_1)(std::string("CppBlog"));

    Trace t1;
//Trace为类,t1为对象
    boost::bind(&Trace::print,boost::ref(t1),_1)(std::string("RichardHe"));
}
结果如下:
//
boost::bind(&Trace::print,trace,_1)(std::string("CppBlog"));
constructor!
constructor by other!
constructor by other!
constructor by other!
tracer::~tracer()
constructor by other!
tracer::~tracer()
tracer::~tracer()
CppBlog
tracer::~tracer()
//
boost::bind(&Trace::print,boost::ref(t1),_1)(std::string("RichardHe"));
constructor!
RichardHe
tracer::~tracer()
tracer::~tracer()

 

(4) 通过 Boost.Bind, 你可以象使用非虚拟函数一样使用虚拟函数,即把它绑定到最先声明该成员函数为虚拟的基类的那个虚拟函数上。这

个绑定器就可以用于所有的派生类。如果你绑定到其它派生类,你就限制了可以使用这个绑定器的类。
(5)bind还可以绑定成员变量。


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


posts - 94, comments - 138, trackbacks - 0, articles - 94

Copyright © RichardHe