Case when a problem occurs
Pay attention to the following C ++ code:
#include <functional>
#include <iostream>
#include <string>
class A {
public:
virtual std::string get() const {
return "A";
}
};
class B : public A {
public:
virtual std::string get() const {
return "B";
}
};
void print(const A &instance) {
std::cout << "It " << instance.get() << std::endl;
}
class State {
A &instance;
public:
State(A &instance) : instance(instance) { }
void run() {
print(instance);
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 .