Virtual member functions and std :: tr1 :: function: How does this work?

Here is a sample code. Note that this Bis a subclass A, and both provide a unique procedure print. Also note mainthat both calls bindare related to &A::print, although in the latter case, a link to is passed B.

#include <iostream>
#include <tr1/functional>

struct A
{
    virtual void print()
    {
        std::cerr << "A" << std::endl;
    }
};

struct B : public A
{
    virtual void print()
    {
        std::cerr << "B" << std::endl;
    }
};

int main (int argc, char * const argv[])
{
    typedef std::tr1::function<void ()> proc_t;

    A a;
    B b;

    proc_t a_print = std::tr1::bind(&A::print, std::tr1::ref(a));
    proc_t b_print = std::tr1::bind(&A::print, std::tr1::ref(b));

    a_print();
    b_print();

    return 0;
}

Here is the result that I see when compiling with GCC 4.2:

A
B

I would think about this correct behavior, but I find it difficult to explain how it works properly, given that I std::tr1::functionwas connected with &A::printin both cases. Can someone please enlighten me?

EDIT: . . , &A::print? vtable vtable ( A B?). , ?

+3
2

, . :

int main ()
{
    A a;
    B b;
    typedef void (A::*fp)();
    fp p = &A::print;
    (a.*p)(); // prints A
    (b.*p)(); // prints B
}

, boost/tr1/std:: - , - . , , , Fast Delegates.

+5

print() virtual, A . print, A, , :

A* ab = &b;
ab->print();

->print . . , . , .:)

+2

Source: https://habr.com/ru/post/1764034/


All Articles