Does std :: bind include parameter data type information in C ++ 11?

Case when a problem occurs

Pay attention to the following C ++ code:

#include <functional>
#include <iostream>
#include <string>

// Superclass
class A {
    public:
    virtual std::string get() const {
        return "A";
    }
};

// Subclass
class B : public A {
    public:
    virtual std::string get() const {
        return "B";
    }
};

// Simple function that prints the object type
void print(const A &instance) {
    std::cout << "It " << instance.get() << std::endl;
}

// Class that holds a reference to an instance of A
class State {
    A &instance;
    public:
    State(A &instance) : instance(instance) { }
    void run() {

        // Invokes print on the instance directly
        print(instance);

        // Creates a new function by binding the instance
        // to the first parameter of the print function, 
        // then calls the function. 
        auto func = std::bind(&print, instance);    
        func();
    }    
};

int main() {
    B instance;
    State state(instance);

    state.run();
}

In this example, we have two classes Aand B. Binherited from the class A. Both classes implement a simple virtual method that returns a type name.

There is also a simple method printthat takes a reference to an instance Aand prints this type.

The class Statecontains a reference to the instance A. The class also has a simple method that calls in printtwo different ways.

Where does it get odd

print . B int , It B, .

print std::bind. - .

, , It A. It B, , .

, std::bind , . , , .

? std::bind ? , , vtable .

+4
1

. :

auto func = std::bind(&print, std::ref(instance));
//                            ^^^^^^^^

: ++, bind . , , , , .

instance. instance , .

, a std::reference_wrapper<A> bind , , . , , , , .

+6

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


All Articles