指针成员和成员函数的最佳用途是什么?

Jon*_*nas 2 c++

指向成员的指针不是很常用,但它们非常强大,你如何使用它们以及你做过的最酷的事情是什么?

编辑: 这不是列出可能的事情,例如列出boost :: bindboost :: function并不好.相反,也许他们很酷的用法?我知道他们自己很酷,但这不是什么意思.

Myk*_*yev 5

我曾经需要使用标准数据作为纯结构进行操作,以便能够存储队列中所有条件的列表.我不得不将结构与GUI和其他过滤器元素等绑定在一起.所以我想出了一个解决方案,其中使用指向成员的指针以及指向成员函数的指针.

假设你有一个

struct Criteria
{
    typedef std::string Criteria::* DataRefType;
    std::string firstname;
    std::string lastname;
    std::string website;
};
Run Code Online (Sandbox Code Playgroud)

比你可以包装标准字段和绑定字段的字符串表示

class Field
{
public:
    Field( const std::string& name,
           Criteria::DataRefType ref ):
        name_( name ),
        ref_( ref )
    {}
    std::string getData( const Criteria& criteria )
    {
        return criteria.*ref_;
    }
    std::string name_;
private:
    Criteria::DataRefType ref_;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以随时注册所有要使用的字段:GUI,序列化,按字段名称比较等.

class Fields
{
public:
    Fields()
    {
        fields_.push_back( Field( "First Name", &Criteria::firstname ) );
        fields_.push_back( Field( "Last Name", &Criteria::lastname ) );
        fields_.push_back( Field( "Website", &Criteria::website ) );
    }
    template < typename TFunction >
    void forEach( TFunction function )
    {
        std::for_each( fields_.begin(), fields_.end(),
                       function );
    }
private:
    std::vector< Field > fields_;
};
Run Code Online (Sandbox Code Playgroud)

通过调用例如fields.forEach( serialization );

GuiWindow( Criteria& criteria ):
    criteria_( criteria )
{
    fields_.forEach( std::bind1st( 
                         std::mem_fun( &GuiWindow::bindWithGui ),
                         this ) );
}
void bindWithGui( Field field )
{
    std::cout << "name " << field.name_
              << " value " << field.getData( criteria_ ) << std::endl;
};
Run Code Online (Sandbox Code Playgroud)