std C ++ 11 :: bind perception of

Found that using std :: bind can achieve a good observer pattern in design mode before the query data.

But the called function bind bound more difficult to implement inheritance using multilevel pointer inheritance.

Sample code is as follows:

Compiler environment: VS2017

 1 #include "pch.h"
 2 #include <iostream>
 3 #include <vector>
 4 #include <functional>
 5 class Base
 6 {
 7 public:
 8     virtual void printMsg() { std::cout << "Base Class" << std::endl; }
 9 };
10 
11 class Derive :public Base
12 {
13 public:
14     virtual void printMsg() { std::cout << "Derive Class" << std::endl; }
15 };
16 
17 class TestClass
18 {
19 public:
20     void PrintMsg(Base **ppbase) { (*ppbase)->printMsg(); }
21 };
22 
23 int main()
24 {
25     std::vector<std::function<void(Base**)>>vec1;
26     TestClass *ptest = new TestClass();
27     Base* pbase = new Base();
28     Base* pder = new new Derive ();
 29      Base ** = & ppbase pbase; // increase subclass 
30      vec1.push_back (STD :: the bind (& the TestClass :: PrintMsg, PTEST, ppbase));
 31 is      * = ppbase PDER; // Assignment 
32      vec1 [ 0 ] (NULL);
 33 is  
34 is      return  0 ;
 35 }

If you delete lines 29 and 31, display Base Class, plus then display Derive Class. This is because at the time of the call, the pointer on the address already changed.

Guess you like

Origin www.cnblogs.com/Kaifangqu/p/11403059.html