对于成员和成员函数的指针,最好的用法是什么? [英] What's the best use you've had with pointer to members and member functions?

查看:125
本文介绍了对于成员和成员函数的指针,最好的用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Pointer to members are not used very much but they are really powerful, how have you used them and what's the coolest things you've done?

编辑:
这不是列出可能的东西,例如列出boost :: bind 和 boost :: function aren' t好。相反可能是一个很酷的用法与他们?我知道他们自己很酷,但这不是这个。

This is not so much to list things that are possible, for example listing boost::bind and boost::function aren't good. Instead maybe a cool usage with them? I know they're very cool in themselves but that's not what this is about.

推荐答案

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

I once was needed to operate with criteria data as pure structure to be able to store the list of all criteria in the queue. And I had to bind the structure with the GUI and other filter elements, etc. So I came up with the solution where pointers to members are used as well as pointers to member functions.

假设您有

struct Criteria
{
    typedef std::string Criteria::* DataRefType;
    std::string firstname;
    std::string lastname;
    std::string website;
};

比你可以包裹条件字段,并用

Than you can wrap criteria field and bind with the string representation of the field with

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_;
};

然后您可以注册所有字段,以便随时使用:GUI,序列化, ,等等。

Then you can register all the fields to use whenever you want: GUI, serialization, comparison by field names, etc.

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_;
};

通过调用 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;
};

这篇关于对于成员和成员函数的指针,最好的用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆