【问题标题】:Distinguish between const and non-const method with same name in boost::bind在 boost::bind 中区分具有相同名称的 const 和非常量方法
【发布时间】:2010-02-14 12:28:07
【问题描述】:

当我将 boost::bind 与声明为 const 和 non-const 的方法名称一起使用时,我遇到了模棱两可的错误,例如

boost::bind( &boost::optional<T>::get, _1 )

我该如何解决这个问题?

【问题讨论】:

    标签: c++ boost boost-bind


    【解决方案1】:

    Boost.Bind 参考的常见问题部分中描述了该问题以及解决方法。

    您还可以使用以下实用功能:

    #include <boost/bind.hpp>
    #include <boost/optional.hpp>
    
    template <class Ret, class Obj>
    Ret (Obj::* const_getter(Ret (Obj::*p) () const)) () const
    {
        return p;
    }
    
    template <class Ret, class Obj>
    Ret (Obj::* nonconst_getter(Ret (Obj::*p)())) ()
    {
        return p;
    }
    
    int main()
    {
        boost::bind( const_getter(&boost::optional<int>::get), _1 );
        boost::bind( nonconst_getter(&boost::optional<int>::get), _1 );
    }
    

    【讨论】:

    • 感谢您的两个建议。我更喜欢 Boost.Bind 常见问题解答中的演员变通方法,现在在我的源代码中使用它。
    • 为了记录,强制转换的解决方法是这样的:假设你想绑定一个函数int Foo::get() const,而不是绑定&amp;Foo::get,绑定static_cast&lt;int(Foo::*)() const&gt;(&amp;Foo::get)
    猜你喜欢
    • 2015-05-28
    • 2014-08-25
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多