Pointer to class data member “::*”

后端 未结 15 1629
清歌不尽
清歌不尽 2020-11-21 11:47

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
         


        
15条回答
  •  隐瞒了意图╮
    2020-11-21 12:10

    One way I've used it is if I have two implementations of how to do something in a class and I want to choose one at run-time without having to continually go through an if statement i.e.

    class Algorithm
    {
    public:
        Algorithm() : m_impFn( &Algorithm::implementationA ) {}
        void frequentlyCalled()
        {
            // Avoid if ( using A ) else if ( using B ) type of thing
            (this->*m_impFn)();
        }
    private:
        void implementationA() { /*...*/ }
        void implementationB() { /*...*/ }
    
        typedef void ( Algorithm::*IMP_FN ) ();
        IMP_FN m_impFn;
    };
    

    Obviously this is only practically useful if you feel the code is being hammered enough that the if statement is slowing things done eg. deep in the guts of some intensive algorithm somewhere. I still think it's more elegant than the if statement even in situations where it has no practical use but that's just my opnion.

提交回复
热议问题