c++ - Set member to same value in all instances of templated structure -


i have following struct:

template <typename t> struct avl_tree {     t data;     int balance;     struct avl_tree <t> *link[2];     int (*comp)(t, t); }; 

what point comp function pointer valid function @ runtime, have instances of struct avl_tree<t> able access function.

int compare(int a, int b) {     return ( - b ); } 

is possible can 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 answer 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 pointer 

in main:

avl_tree<int>::comp = compare;//set static member function pointer function use 

in response previous question, here how 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

declare comp static:

template <typename t> struct avl_tree {     t data;     int balance;     struct avl_tree <t> *link[2];     static int (*comp)(t, t); }; template <typename t> int(*::comp)(<t>, <t>); 

you can later assign particular template instance with:

avl_tree<int>::comp = int_compare; 

see this question , this outside site more information initialization of static members of template classes.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -