Created
March 20, 2013 17:01
-
-
Save chunkyguy/5206358 to your computer and use it in GitHub Desktop.
C++ pointer to member function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using std::function for callback | |
#include <iostream> | |
#include <utility> | |
class Client; | |
// Calculator server | |
class Server{ | |
public: | |
typedef void (Client::*CB)(int result); | |
void process(int x, int y, CB callback, Client *a){ | |
std::cout << "Server::process" << std::endl; | |
(a->*callback)(x + y); | |
} | |
}; | |
class Client{ | |
public: | |
Client(int c) : | |
no(c) | |
{ } | |
void start(){ | |
std::cout << "Client::Start" << no << std::endl; | |
s.process(21, 27, &Client::print, this); | |
} | |
void print(int result){ | |
std::cout << "Client::print: " << no << result << std::endl; | |
} | |
private: | |
Server s; | |
int no; | |
}; | |
int main(){ | |
Client c1(1), c2(2); | |
c1.start(); | |
c2.start(); | |
std::cout << "Done" << std::endl; | |
return 0; | |
} | |
///EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment