Created
May 17, 2017 18:54
-
-
Save JeroenDM/21e1ba0553f5c02534d1cd40ad7c780c to your computer and use it in GitHub Desktop.
Test Boost.Function to implement a private callback function in a class
This file contains 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
#include <iostream> | |
#include <boost/function.hpp> | |
#include <vector> | |
using namespace std; | |
// Simple Point class | |
class Point | |
{ | |
int _value; | |
public: | |
Point(int val) : _value(val) {} | |
~Point() {} | |
void setValue(int val) { _value = val; } | |
int getValue() { return _value; } | |
}; | |
typedef boost::function<int (Point x, Point y)> CostFunction; | |
// Simple Graph class | |
// Is hard coded to contain two points | |
class Graph | |
{ | |
CostFunction _cost_function; | |
vector<Point> _trajectory; | |
void _fill_trajectory(); | |
public: | |
Graph(); | |
Graph(CostFunction input_function); | |
~Graph(); | |
int add_two_points(); | |
}; | |
// Graph class implementation | |
void Graph::_fill_trajectory() | |
{ | |
Point o1(2), o2(9); | |
_trajectory.push_back(o1); | |
_trajectory.push_back(o2); | |
} | |
Graph::Graph() { | |
_fill_trajectory(); | |
} | |
Graph::~Graph() {} | |
Graph::Graph(CostFunction input_function) | |
{ | |
_cost_function = input_function; | |
_fill_trajectory(); | |
} | |
int Graph::add_two_points() | |
{ | |
if(_cost_function) | |
{ | |
cout << "Graph::There is a callback defined!" << endl; | |
int a = _trajectory[0].getValue(); | |
int b = _trajectory[1].getValue(); | |
return _cost_function(a, b); | |
} | |
else | |
{ | |
cout << "Graph::No callback defined!" << endl; | |
return 99; | |
} | |
} | |
// Define callback function to pass to Graph constructor | |
int add_two_points_callback(Point &p1, Point &p2) | |
{ | |
return p1.getValue() + p2.getValue(); | |
} | |
// Main | |
int main( ) | |
{ | |
// Create graph without given a callback | |
// Graph::add_two_points will return 99 | |
Graph g1; | |
cout << "main::Non callback: " << g1.add_two_points() << endl; | |
// Create graph with callback function | |
// Graph::add_two_points will return sum of two values of points in graph | |
Graph g2(add_two_points_callback); | |
cout << "main::Callback is defined " << g2.add_two_points() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know, there is no copy constructor...