I have the following struct:
template <typename T> struct avl_tree {
T data;
int balance;
struct avl_tree <T> *Link[2];
int (*comp)(T, T);
};
What I would like to do is to point the comp
function pointer to a valid function at runtime, then have all instances of struct avl_tree<T>
to be able to access this function.
int compare(int a, int b) {
return ( a - b );
}
Is this possible to do so that I can do something like:
avl_tree<int> tree(new avl_tree<int>);
tree = insert(tree, 9);
std::cout << tree->comp(tree->data, 9) << '\n';//Should print 0
Finally got the answer to this. Solution:
in struct avl_tree:
typedef int (*compare)(T, T);
static compare comp;
above main:
template <typename T> int (*avl_tree<T>::comp)(T, T);//Initialise the pointer
in main:
avl_tree<int>::comp = compare;//Set the static member function pointer to the function to use
In response to my previous question, here is how you can use it:
avl_tree<int> tree(new avl_tree<int>);
tree = insert(tree, 9);
std::cout << avl_tree<int>::comp(tree->data, 9) << '\n';//Should print 0
Simple :D