Passing functions via pointers

Hello.
I was wondering: how should I call a function stored in a separate file that of whom I know nothing but the header?

If I had a function for a queue that takes void* (and therefore I can put anything into it) and I wanted to call the destruction function of the data I'm queueing passing it as a parameter to the destruction function of the queue itself, how should I call it?

This is the header
 
  void queue_destruction(queue_t* queue, void (internal_data_destr)(void*))


When I want to call it, how do I do it? If I write
1
2
3
  queue_t* some_queue = create_queue();
  // create and store 100 stacks in queue
  void queue_destruction(some_queue,(*stack_destruction)(stack));

Valgrind says "invalid use of void expression" at queue_destruction line.
If you're using a library that has the implementations of your .h file, then everything would probably be fine in your example except for your stray void before your function call.

If you aren't using a library then you're going to have to do some more magic.
Use std::queue<> http://en.cppreference.com/w/cpp/container/queue


For some obscure reason, if you must use that C implementation of queue:

write a type-unsafe stack clean-up function that accepts a void*
in the function, cast the void* to a pointer to a stack
pass a pointer to that function to queue_destruction()

Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <queue>

using queue_t = std::queue<void*> ;

queue_t* create_queue() { return new queue_t ; }

void push_queue( queue_t* q, void* item ) { q->push(item) ; }

void destroy_queue( queue_t* q, void (internal_data_destr)(void*) )
{
    while( !q->empty() ) { internal_data_destr( q->front() ) ; q->pop() ; }
    delete q ;
}

struct my_stack
{
    my_stack() { std::cout << "my_stack::constructor " << this << '\n' ; }
    ~my_stack() { std::cout << "my_stack::destructor " << this << '\n' ; }
};

void delete_my_stack( void* p ) { delete static_cast<my_stack*>(p) ; }

int main()
{
    queue_t* q = create_queue() ;

    for( int i = 0 ; i < 5 ; ++i ) push_queue( q, new my_stack ) ;
    std::cout << "\n-----------------\n" ;
    destroy_queue( q, delete_my_stack ) ;
}

http://coliru.stacked-crooked.com/a/01decd88bdfe57ea
Topic archived. No new replies allowed.